diff --git a/notNeededPackages.json b/notNeededPackages.json index 32b639258f..c0d0abf55d 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -2850,6 +2850,12 @@ "sourceRepoURL": "https://github.com/stream-utils/raw-body", "asOfVersion": "2.3.0" }, + { + "libraryName": "re2", + "typingsPackageName": "re2", + "sourceRepoURL": "https://github.com/uhop/node-re2", + "asOfVersion": "1.10.3" + }, { "libraryName": "react-chartjs-2", "typingsPackageName": "react-chartjs-2", diff --git a/types/async-eventemitter/async-eventemitter-tests.ts b/types/async-eventemitter/async-eventemitter-tests.ts new file mode 100644 index 0000000000..870d3ccfa0 --- /dev/null +++ b/types/async-eventemitter/async-eventemitter-tests.ts @@ -0,0 +1,38 @@ +import * as AsyncEventEmitter from 'async-eventemitter'; + +const ee = new AsyncEventEmitter<{ + sync: (a: string) => void; + // "sync-multiple": (a: string, b: number) => void, + async: (data?: { a: string; b: boolean }) => Promise; + // "illegal-async": (data: string, data2: number) => Promise, + 'premature-resolve': ( + data: number, + resolve?: (result: any) => void, + ) => Promise; + 'premature-resolve-empty': ( + data: number, + resolve?: () => void, + ) => Promise; + 'is-empty': () => any; +}>(); + +ee.emit('sync', 'yes'); +ee.emit('async', { a: 'a', b: true }); +ee.emit('async'); +ee.emit('is-empty'); +ee.emit('premature-resolve', 1); + +(async () => { + // await new Promise((resolve) => ee.emit("async", undefined, resolve)); // fail + // await new Promise((resolve) => ee.emit("premature-resolve", undefined, resolve)); // Should fail + await new Promise(resolve => ee.emit('premature-resolve', 1, resolve)); +})(); + +ee.on('is-empty', () => {}); +ee.on('async', async data => { + `Reach the end of async function and ${data}`; +}); +ee.on('premature-resolve', async (data, resolve) => { + if (resolve) resolve(true); + 'does not reach here'; +}); diff --git a/types/async-eventemitter/index.d.ts b/types/async-eventemitter/index.d.ts new file mode 100644 index 0000000000..3d41ec268f --- /dev/null +++ b/types/async-eventemitter/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for async-eventemitter 0.2 +// Project: https://www.npmjs.com/package/async-eventemitter (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: patarapolw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.5 + +import { EventEmitter } from "events"; + +/** + * The API and behavior of AsyncEventEmitter is as far as possible and meaningful identical to + * that of the native EventEmitter. However there are some important differences which should be noted. + * - Data sent to event listeners (eg emit(data)) must always be zero or one argument, and can not be a function. + * - Event listeners will always recieve the data object, which may or may not be undefined. + * - The second argument can only be a callback, and will only be supplied if the event listener has an arity of two or more (eg function(e, next){}). + * - Event listeners with an arity of one or zero (eg without a callback argument specified) will be treated as synchronous. + * - Even if all event listeners are synchronous, they will still be executed asynchronously (through setImmediate) and thus code suceeding .emit() will be executed before any event listeners. + * - Interupt the callback chain in async listeners by calling the callback with the error as the first parameter; in sync listeners by throwing an Error. + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ +export = AsyncEventEmitter; + +/** + * An EventEmitter that supports serial execution of asynchronous event listeners. + * It also supports event listeners without callbacks (synchronous), as well as + * interrupting the call-chain (similar to the DOM's e.stopPropagation()). + */ +declare class AsyncEventEmitter< + T extends AsyncEventEmitter.EventMap +> extends EventEmitter { + /** + * Executes all listeners for the event in order with the supplied data argument. + * The optional callback is called when all of the listeners are done. + * @param event EventMap key (event name) + * @param args EventMap parameters + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ + emit( + event: E & string, + ...args: Parameters + ): boolean; + /** + * Adds a listener to the beginning of the listeners array for the specified event. + * @param event EventMap key (event name) + * @param listener EventMap value (event function) + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ + first(event: E & string, listener: T[E]): this; + /** + * Adds a listener at the specified index in the listeners array for the specified event. + * @param event EventMap key (event name) + * @param index Index to insert at + * @param listener EventMap value (event function) + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ + at(event: E & string, index: number, listener: T[E]): this; + /** + * Adds a listener before the target listener in the listeners array for the specified event. + * @param event EventMap key (event name) + * @param target Listener to insert before + * @param listener EventMap value (event function) + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ + before( + event: E & string, + target: T[E], + listener: T[E], + ): this; + /** + * Adds a listener after the target listener in the listeners array for the specified event. + * @param event EventMap key (event name) + * @param target Listener to insert before + * @param listener EventMap value (event function) + * @see https://www.npmjs.com/package/async-eventemitter#important-differences-between-asynceventemitter-the-native-eventemitter + */ + after( + event: E & string, + target: T[E], + listener: T[E], + ): this; + + // https://github.com/andywer/typed-emitter/blob/master/index.d.ts + addListener(event: E & string, listener: T[E]): this; + on(event: E & string, listener: T[E]): this; + once(event: E & string, listener: T[E]): this; + prependListener(event: E & string, listener: T[E]): this; + prependOnceListener( + event: E & string, + listener: T[E], + ): this; + + removeAllListeners(event?: keyof T & string): this; + removeListener(event: E & string, listener: T[E]): this; + + eventNames(): Array; + listeners(event: E & string): Array; + listenerCount(event: keyof T & string): number; + + getMaxListeners(): number; + setMaxListeners(maxListeners: number): this; +} + +declare namespace AsyncEventEmitter { + type AsyncListener = ((data: T, callback: (result?: R) => void) => Promise) | ((data: T, callback: (result?: R) => void) => void); + interface EventMap { + [event: string]: AsyncListener; + } +} diff --git a/types/async-eventemitter/tsconfig.json b/types/async-eventemitter/tsconfig.json new file mode 100644 index 0000000000..e0c4d2391d --- /dev/null +++ b/types/async-eventemitter/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "async-eventemitter-tests.ts" + ] +} diff --git a/types/re2/tslint.json b/types/async-eventemitter/tslint.json similarity index 100% rename from types/re2/tslint.json rename to types/async-eventemitter/tslint.json diff --git a/types/cleave.js/options/index.d.ts b/types/cleave.js/options/index.d.ts index b1dc95920b..3bb375a6ae 100644 --- a/types/cleave.js/options/index.d.ts +++ b/types/cleave.js/options/index.d.ts @@ -44,6 +44,7 @@ export interface CleaveOptions { copyDelimiter?: boolean; delimiter?: string; delimiters?: ReadonlyArray; + delimiterLazyShow?: boolean; initValue?: any; lowercase?: boolean; numericOnly?: boolean; diff --git a/types/compass-vertical-rhythm/compass-vertical-rhythm-tests.ts b/types/compass-vertical-rhythm/compass-vertical-rhythm-tests.ts new file mode 100644 index 0000000000..7d943e56b4 --- /dev/null +++ b/types/compass-vertical-rhythm/compass-vertical-rhythm-tests.ts @@ -0,0 +1,54 @@ +import compassVerticalRhythm = require('compass-vertical-rhythm'); + +compassVerticalRhythm({ baseFontSize: '16px' }); +compassVerticalRhythm({ baseLineHeight: 1.5 }); +compassVerticalRhythm({ baseLineHeight: '16px' }); +compassVerticalRhythm({ rhythmUnit: '%' }); +compassVerticalRhythm({ rhythmUnit: 'ch' }); +compassVerticalRhythm({ rhythmUnit: 'em' }); +compassVerticalRhythm({ rhythmUnit: 'ex' }); +compassVerticalRhythm({ rhythmUnit: 'px' }); +compassVerticalRhythm({ rhythmUnit: 'rem' }); +compassVerticalRhythm({ rhythmUnit: 'vh' }); +compassVerticalRhythm({ rhythmUnit: 'vmin' }); +compassVerticalRhythm({ rhythmUnit: 'vw' }); +compassVerticalRhythm({ defaultRhythmBorderWidth: '16px' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'solid' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'none' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'hidden' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'dashed' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'dotted' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'double' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'groove' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'ridge' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'inset' }); +compassVerticalRhythm({ defaultRhythmBorderStyle: 'outset' }); +compassVerticalRhythm({ roundToNearestHalfLine: true }); +compassVerticalRhythm({ minLinePadding: '2px' }); + +const cvr = compassVerticalRhythm({ + baseFontSize: '16px', + baseLineHeight: 1.5, + rhythmUnit: 'rem', + defaultRhythmBorderWidth: '1px', + defaultRhythmBorderStyle: 'solid', + roundToNearestHalfLine: true, + minLinePadding: '2px', +}); + +cvr.rhythm(); +cvr.rhythm(1); +cvr.rhythm(1, '16px'); +cvr.rhythm(1, '16px', 4); + +cvr.establishBaseline().fontSize; +cvr.establishBaseline().lineHeight; + +cvr.linesForFontSize('16px'); + +cvr.adjustFontSizeTo('32px', 1, '16px').fontSize; +cvr.adjustFontSizeTo('32px', 1, '16px').lineHeight; +cvr.adjustFontSizeTo('32px', 'auto', '16px'); +cvr.adjustFontSizeTo('32px', null, '16px'); +cvr.adjustFontSizeTo('32px', 1); +cvr.adjustFontSizeTo('32px'); diff --git a/types/compass-vertical-rhythm/index.d.ts b/types/compass-vertical-rhythm/index.d.ts new file mode 100644 index 0000000000..699e48045b --- /dev/null +++ b/types/compass-vertical-rhythm/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for compass-vertical-rhythm 1.4 +// Project: https://github.com/KyleAMathews/compass-vertical-rhythm +// Definitions by: Luis Rodrigues +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = compassVerticalRhythm; + +interface Options { + baseFontSize?: string; + baseLineHeight?: number | string; + rhythmUnit?: '%' | 'em' | 'ex' | 'ch' | 'px' | 'rem' | 'vw' | 'vh' | 'vmin'; + defaultRhythmBorderWidth?: string; + defaultRhythmBorderStyle?: + | 'solid' + | 'none' + | 'hidden' + | 'dashed' + | 'dotted' + | 'double' + | 'groove' + | 'ridge' + | 'inset' + | 'outset'; + roundToNearestHalfLine?: boolean; + minLinePadding?: string; +} + +interface VerticalRhythmStyles { + fontSize: string; + lineHeight: string; +} + +interface VerticalRhythm { + rhythm(lines?: number, fontSize?: string, offset?: number): number; + establishBaseline(): VerticalRhythmStyles; + linesForFontSize(fontSize: string): number; + adjustFontSizeTo(toSize: string, lines?: number | 'auto' | null, fromSize?: string): VerticalRhythmStyles; +} + +declare function compassVerticalRhythm(options: Options): VerticalRhythm; diff --git a/types/compass-vertical-rhythm/tsconfig.json b/types/compass-vertical-rhythm/tsconfig.json new file mode 100644 index 0000000000..a945bfd192 --- /dev/null +++ b/types/compass-vertical-rhythm/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", "compass-vertical-rhythm-tests.ts"] +} diff --git a/types/compass-vertical-rhythm/tslint.json b/types/compass-vertical-rhythm/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compass-vertical-rhythm/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draftjs-to-html/draftjs-to-html-tests.ts b/types/draftjs-to-html/draftjs-to-html-tests.ts new file mode 100644 index 0000000000..579e8f9138 --- /dev/null +++ b/types/draftjs-to-html/draftjs-to-html-tests.ts @@ -0,0 +1,21 @@ +import draftToHtml from 'draftjs-to-html'; + +const editorContent = { + blocks: [ + { + key: '355iu', + text: 'test', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [], + entityRanges: [], + data: { + 'text-align': 'center', + }, + }, + ], + entityMap: {}, +}; + +// $ExpectType string +draftToHtml(editorContent); diff --git a/types/draftjs-to-html/index.d.ts b/types/draftjs-to-html/index.d.ts new file mode 100644 index 0000000000..fd5b6e8f30 --- /dev/null +++ b/types/draftjs-to-html/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for draftjs-to-html 0.8 +// Project: https://github.com/jpuri/draftjs-to-html#readme +// Definitions by: Ivan Zverev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import { RawDraftContentState } from 'draft-js'; + +interface HashtagConfig { + trigger?: string; + separator?: string; +} + +declare function draftToHtml( + editorContent: RawDraftContentState, + hashtagConfig?: HashtagConfig, + directional?: boolean, + customEntityTransform?: (...args: any[]) => any, +): string; + +export = draftToHtml; diff --git a/types/draftjs-to-html/tsconfig.json b/types/draftjs-to-html/tsconfig.json new file mode 100644 index 0000000000..3cc389a199 --- /dev/null +++ b/types/draftjs-to-html/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "draftjs-to-html-tests.ts" + ] +} diff --git a/types/draftjs-to-html/tslint.json b/types/draftjs-to-html/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/draftjs-to-html/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index 3780b8c899..dc9e556f07 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for non-npm package ej.web.all 17.2 +// Type definitions for non-npm package ej.web.all 17.3 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ /*! * filename: ej.web.all.d.ts -* version : 17.2.0.46 +* version : 17.3.0.9-beta * Copyright Syncfusion Inc. 2001 - 2019. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -37663,7 +37663,7 @@ declare namespace ej { /** Specifies the print option of the report. * @Default {ej.ReportViewer.PrintOptions.Default} */ - printOptions?: ej.ReportViewer.PrintOptions|string; + printOption?: ej.ReportViewer.PrintOptions|string; /** Specifies the processing mode of the report. * @Default {ej.ReportViewer.ProcessingMode.Remote} @@ -38247,6 +38247,16 @@ declare namespace ej { * @Default {auto} */ popupWidth?: string; + + /** Specifies the width of the parameter item. By default, the item width value is set as "185px". + * @Default {185px} + */ + itemWidth?: string; + + /** Specifies the width of the parameter label. By default, the parameter label width value is set as "110px". + * @Default {110px} + */ + labelWidth?: string; } enum ExportOptions { @@ -38254,8 +38264,8 @@ declare namespace ej { ///Specifies the All property in ExportOptions to get all available options. All, - ///Specifies the PDF property in ExportOptions to get PDF option. - PDF, + ///Specifies the Pdf property in ExportOptions to get Pdf option. + Pdf, ///Specifies the Word property in ExportOptions to get Word option. Word, @@ -38263,8 +38273,17 @@ declare namespace ej { ///Specifies the Excel property in ExportOptions to get Excel option. Excel, - ///Specifies the HTML property in ExportOptions to get HTML option. - HTML + ///Specifies the Html property in ExportOptions to get Html option. + Html, + + ///Specifies the PPT property in ExportOptions to get PPT option. + PPT, + + ///Specifies the CSV property in ExportOptions to get CSV option. + CSV, + + ///Specifies the customItems property in ExportOptions to get customItems option. + CustomItems } @@ -49665,6 +49684,11 @@ declare namespace ej { */ locale?: string; + /** Shows or hides the create, edit, and delete options in data source and dataset panels. + * @Default {ej.ReportDesigner.Permission.All} + */ + permissionSettings?: PermissionSettings; + /** Gets or sets the list of custom data extension items. * @Default {[]} */ @@ -49680,6 +49704,11 @@ declare namespace ej { */ reportPath?: string; + /** Gets or sets the report type. + * @Default {ej.ReportDesigner.ReportType.RDL} + */ + reportType?: string; + /** Gets or sets the reports server URL. * @Default {null} */ @@ -49872,6 +49901,14 @@ declare namespace ej { showConfigurePane?: boolean; } + export interface PermissionSettings { + + /** Shows or hides the create, edit and delete options in data source pane with the help of ej.ReportDesigner.Permission enum. + * @Default {ej.ReportDesigner.Permission.All} + */ + dataSource?: ej.ReportDesigner.Permission|string; + } + export interface ReportDataExtension { /** Gets or sets the name of the datasource type. @@ -49946,6 +49983,22 @@ declare namespace ej { templateId?: string; } + enum Permission { + + ///Shows or hides create option in data source pane. + Create, + + ///Shows or hides the edit option in data source pane. + Edit, + + ///Shows or hides the delete option in data source pane. + Delete, + + ///Shows all the options in data source pane. + All + } + + enum ToolbarItems { ///Creates a new, blank report. diff --git a/types/gapi.client.sheets/gapi.client.sheets-tests.ts b/types/gapi.client.sheets/gapi.client.sheets-tests.ts index 032a8793ad..72fe871bc1 100644 --- a/types/gapi.client.sheets/gapi.client.sheets-tests.ts +++ b/types/gapi.client.sheets/gapi.client.sheets-tests.ts @@ -1,7 +1,7 @@ /* This is stub file for gapi.client.{{=it.name}} definition tests */ /* IMPORTANT. -* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. -* In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator +* This file was generated by https://github.com/Maxim-Mazurok/google-api-typings-generator/tree/patch-1. Please do not edit it manually. +* In case of any problems please post issue to https://github.com/Maxim-Mazurok/google-api-typings-generator or https://github.com/Bolisov/google-api-typings-generator **/ gapi.load('client', () => { /** now we can use gapi.client */ @@ -12,13 +12,13 @@ gapi.load('client', () => { /** declare client_id registered in Google Developers Console */ const client_id = '<>'; const scope = [ - /** View and manage the files in your Google Drive */ + /** See, edit, create, and delete all of your Google Drive files */ 'https://www.googleapis.com/auth/drive', /** View and manage Google Drive files and folders that you have opened or created with this app */ 'https://www.googleapis.com/auth/drive.file', - /** View the files in your Google Drive */ + /** See and download all your Google Drive files */ 'https://www.googleapis.com/auth/drive.readonly', - /** View and manage your spreadsheets in Google Drive */ + /** See, edit, create, and delete your spreadsheets in Google Drive */ 'https://www.googleapis.com/auth/spreadsheets', /** View your Google Spreadsheets */ 'https://www.googleapis.com/auth/spreadsheets.readonly', @@ -57,11 +57,11 @@ gapi.load('client', () => { * collaborator changes. If there are no collaborators, the spreadsheet * should reflect your changes. */ - await gapi.client.spreadsheets.batchUpdate({ + await gapi.client.sheets.spreadsheets.batchUpdate({ spreadsheetId: "spreadsheetId", }); /** Creates a spreadsheet, returning the newly created spreadsheet. */ - await gapi.client.spreadsheets.create({ + await gapi.client.sheets.spreadsheets.create({ }); /** * Returns the spreadsheet at the given ID. @@ -86,7 +86,7 @@ gapi.load('client', () => { * return only the portions of the spreadsheet that intersect the requested * ranges. Ranges are specified using A1 notation. */ - await gapi.client.spreadsheets.get({ + await gapi.client.sheets.spreadsheets.get({ includeGridData: true, ranges: "ranges", spreadsheetId: "spreadsheetId", @@ -115,7 +115,7 @@ gapi.load('client', () => { * For large spreadsheets, it is recommended to retrieve only the specific * fields of the spreadsheet that you want. */ - await gapi.client.spreadsheets.getByDataFilter({ + await gapi.client.sheets.spreadsheets.getByDataFilter({ spreadsheetId: "spreadsheetId", }); } diff --git a/types/gapi.client.sheets/index.d.ts b/types/gapi.client.sheets/index.d.ts index 46aaa2a246..9a057e7288 100644 --- a/types/gapi.client.sheets/index.d.ts +++ b/types/gapi.client.sheets/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for non-npm package Google Google Sheets API v4 4.0 // Project: https://developers.google.com/sheets/ // Definitions by: Bolisov Alexey +// Maxim Mazurok // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // IMPORTANT -// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. -// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator +// This file was generated by https://github.com/Maxim-Mazurok/google-api-typings-generator/tree/patch-1. Please do not edit it manually. +// In case of any problems please post issue to https://github.com/Maxim-Mazurok/google-api-typings-generator or https://github.com/Bolisov/google-api-typings-generator // Generated from: https://sheets.googleapis.com/$discovery/rest?version=v4 /// @@ -16,8 +17,6 @@ declare namespace gapi.client { function load(name: "sheets", version: "v4"): PromiseLike; function load(name: "sheets", version: "v4", callback: () => any): void; - const spreadsheets: sheets.SpreadsheetsResource; - namespace sheets { interface AddBandingRequest { /** @@ -36,7 +35,7 @@ declare namespace gapi.client { * The chart that should be added to the spreadsheet, including the position * where it should be placed. The chartId * field is optional; if one is not set, an id will be randomly generated. (It - * is an error to specify the ID of a chart that already exists.) + * is an error to specify the ID of an embedded object that already exists.) */ chart?: EmbeddedChart; } @@ -50,6 +49,14 @@ declare namespace gapi.client { /** The rule to add. */ rule?: ConditionalFormatRule; } + interface AddDimensionGroupRequest { + /** The range over which to create a group. */ + range?: DimensionRange; + } + interface AddDimensionGroupResponse { + /** All groups of a dimension after adding a group to that dimension. */ + dimensionGroups?: DimensionGroup[]; + } interface AddFilterViewRequest { /** * The filter to add. The filterViewId @@ -161,7 +168,7 @@ declare namespace gapi.client { /** The id of the banded range. */ bandedRangeId?: number; /** - * Properties for column bands. These properties will be applied on a column- + * Properties for column bands. These properties are applied on a column- * by-column basis throughout all the columns in the range. At least one of * row_properties or column_properties must be specified. */ @@ -169,7 +176,7 @@ declare namespace gapi.client { /** The range over which these properties are applied. */ range?: GridRange; /** - * Properties for row bands. These properties will be applied on a row-by-row + * Properties for row bands. These properties are applied on a row-by-row * basis throughout all the rows in the range. At least one of * row_properties or column_properties must be specified. */ @@ -212,6 +219,8 @@ declare namespace gapi.client { title?: string; /** The axis title text position. */ titleTextPosition?: TextPosition; + /** The view window options for this axis. */ + viewWindowOptions?: ChartAxisViewWindowOptions; } interface BasicChartDomain { /** @@ -223,6 +232,20 @@ declare namespace gapi.client { reversed?: boolean; } interface BasicChartSeries { + /** + * The color for elements (i.e. bars, lines, points) associated with this + * series. If empty, a default color is used. + */ + color?: Color; + /** + * The line style of this series. Valid only if the + * chartType is AREA, + * LINE, or SCATTER. + * COMBO charts are also supported if the + * series chart type is + * AREA or LINE. + */ + lineStyle?: LineStyle; /** The data being visualized in this chart series. */ series?: ChartData; /** @@ -287,7 +310,7 @@ declare namespace gapi.client { series?: BasicChartSeries[]; /** * The stacked type for charts that support vertical stacking. - * Applies to Area, Bar, Column, and Stepped Area charts. + * Applies to Area, Bar, Column, Combo, and Stepped Area charts. */ stackedType?: string; /** @@ -400,7 +423,7 @@ declare namespace gapi.client { requests?: Request[]; /** * True if grid data should be returned. Meaningful only if - * if include_spreadsheet_response is 'true'. + * if include_spreadsheet_in_response is 'true'. * This parameter is ignored if a field mask was set in the request. */ responseIncludeGridData?: boolean; @@ -543,7 +566,7 @@ declare namespace gapi.client { interface BooleanRule { /** * The condition of the rule. If the condition evaluates to true, - * the format will be applied. + * the format is applied. */ condition?: BooleanCondition; /** @@ -616,7 +639,7 @@ declare namespace gapi.client { domain?: ChartData; /** * The data containing the bubble group IDs. All bubbles with the same group - * ID will be drawn in the same color. If bubble_sizes is specified then + * ID are drawn in the same color. If bubble_sizes is specified then * this field must also be specified but may contain blank values. * This field is optional. */ @@ -693,8 +716,8 @@ declare namespace gapi.client { */ effectiveFormat?: CellFormat; /** - * The effective value of the cell. For cells with formulas, this will be - * the calculated value. For cells with literals, this will be + * The effective value of the cell. For cells with formulas, this is + * the calculated value. For cells with literals, this is * the same as the user_entered_value. * This field is read-only. */ @@ -731,7 +754,7 @@ declare namespace gapi.client { * the properties of the cell unless explicitly changed). * * When writing, the new runs will overwrite any prior runs. When writing a - * new user_entered_value, previous runs will be erased. + * new user_entered_value, previous runs are erased. */ textFormatRuns?: TextFormatRun[]; /** @@ -771,6 +794,20 @@ declare namespace gapi.client { /** The wrap strategy for the value in the cell. */ wrapStrategy?: string; } + interface ChartAxisViewWindowOptions { + /** + * The maximum numeric value to be shown in this view window. If unset, will + * automatically determine a maximum value that looks good for the data. + */ + viewWindowMax?: number; + /** + * The minimum numeric value to be shown in this view window. If unset, will + * automatically determine a minimum value that looks good for the data. + */ + viewWindowMin?: number; + /** The view window's mode. */ + viewWindowMode?: string; + } interface ChartData { /** The source ranges of the data. */ sourceRange?: ChartSourceRange; @@ -783,7 +820,8 @@ declare namespace gapi.client { * with length 1. * The domain (if it exists) & all series must have the same number * of source ranges. If using more than one source range, then the source - * range at a given offset must be contiguous across the domain and series. + * range at a given offset must be in order and contiguous across the domain + * and series. * * For example, these are valid configurations: * @@ -862,11 +900,18 @@ declare namespace gapi.client { * This field is optional. */ titleTextPosition?: TextPosition; + /** A treemap chart specification. */ + treemapChart?: TreemapChartSpec; + /** A waterfall chart specification. */ + waterfallChart?: WaterfallChartSpec; } interface ClearBasicFilterRequest { /** The sheet ID on which the basic filter should be cleared. */ sheetId?: number; } + // tslint:disable-next-line:no-empty-interface + interface ClearValuesRequest { + } interface ClearValuesResponse { /** * The range (in A1 notation) that was cleared. @@ -916,8 +961,8 @@ declare namespace gapi.client { relativeDate?: string; /** * A value the condition is based on. - * The value will be parsed as if the user typed into a cell. - * Formulas are supported (and must begin with an `=`). + * The value is parsed as if the user typed into a cell. + * Formulas are supported (and must begin with an `=` or a '+'). */ userEnteredValue?: string; } @@ -927,7 +972,7 @@ declare namespace gapi.client { /** The formatting will vary based on the gradients in the rule. */ gradientRule?: GradientRule; /** - * The ranges that will be formatted if the condition is true. + * The ranges that are formatted if the condition is true. * All the ranges must be on the same grid. */ ranges?: GridRange[]; @@ -1008,6 +1053,10 @@ declare namespace gapi.client { /** True if invalid data should be rejected. */ strict?: boolean; } + interface DateTimeRule { + /** The type of date-time grouping to apply. */ + type?: string; + } interface DeleteBandingRequest { /** The ID of the banded range to delete. */ bandedRangeId?: number; @@ -1033,10 +1082,31 @@ declare namespace gapi.client { /** The metadata that was deleted. */ deletedDeveloperMetadata?: DeveloperMetadata[]; } + interface DeleteDimensionGroupRequest { + /** The range of the group to be deleted. */ + range?: DimensionRange; + } + interface DeleteDimensionGroupResponse { + /** All groups of a dimension after deleting a group from that dimension. */ + dimensionGroups?: DimensionGroup[]; + } interface DeleteDimensionRequest { /** The dimensions to delete from the sheet. */ range?: DimensionRange; } + interface DeleteDuplicatesRequest { + /** + * The columns in the range to analyze for duplicate values. If no columns are + * selected then all columns are analyzed for duplicates. + */ + comparisonColumns?: DimensionRange[]; + /** The range to remove duplicates rows from. */ + range?: GridRange; + } + interface DeleteDuplicatesResponse { + /** The number of duplicate rows removed. */ + duplicatesRemovedCount?: number; + } interface DeleteEmbeddedObjectRequest { /** The ID of the embedded object to delete. */ objectId?: number; @@ -1161,6 +1231,26 @@ declare namespace gapi.client { */ visibility?: string; } + interface DimensionGroup { + /** + * This field is true if this group is collapsed. A collapsed group remains + * collapsed if an overlapping group at a shallower depth is expanded. + * + * A true value does not imply that all dimensions within the group are + * hidden, since a dimension's visibility can change independently from this + * group property. However, when this property is updated, all dimensions + * within it are set to hidden if this field is true, or set to visible if + * this field is false. + */ + collapsed?: boolean; + /** + * The depth of the group, representing how many groups have a range that + * wholly contains the range of this group. + */ + depth?: number; + /** The range over which this group exists. */ + range?: DimensionRange; + } interface DimensionProperties { /** The developer metadata associated with a single row or column. */ developerMetadata?: DeveloperMetadata[]; @@ -1234,7 +1324,7 @@ declare namespace gapi.client { } interface EmbeddedObjectPosition { /** - * If true, the embedded object will be put on a new sheet whose ID + * If true, the embedded object is put on a new sheet whose ID * is chosen for you. Used only when writing. */ newSheet?: boolean; @@ -1422,6 +1512,8 @@ declare namespace gapi.client { interface GridProperties { /** The number of columns in the grid. */ columnCount?: number; + /** True if the column grouping control toggle is shown after the group. */ + columnGroupControlAfter?: boolean; /** The number of columns that are frozen in the grid. */ frozenColumnCount?: number; /** The number of rows that are frozen in the grid. */ @@ -1430,6 +1522,8 @@ declare namespace gapi.client { hideGridlines?: boolean; /** The number of rows in the grid. */ rowCount?: number; + /** True if the row grouping control toggle is shown after the group. */ + rowGroupControlAfter?: boolean; } interface GridRange { /** The end column (exclusive) of the range, or not set if unbounded. */ @@ -1475,6 +1569,22 @@ declare namespace gapi.client { */ showItemDividers?: boolean; } + interface HistogramRule { + /** + * The maximum value at which items are placed into buckets + * of constant size. Values above end are lumped into a single bucket. + * This field is optional. + */ + end?: number; + /** The size of the buckets that are created. Must be positive. */ + interval?: number; + /** + * The minimum value at which items are placed into buckets + * of constant size. Values below start are lumped into a single bucket. + * This field is optional. + */ + start?: number; + } interface HistogramSeries { /** * The color of the column representing this series in each bucket. @@ -1537,6 +1647,33 @@ declare namespace gapi.client { */ maxIterations?: number; } + interface LineStyle { + /** The dash type of the line. */ + type?: string; + /** The thickness of the line, in px. */ + width?: number; + } + interface ManualRule { + /** + * The list of group names and the corresponding items from the source data + * that map to each group name. + */ + groups?: ManualRuleGroup[]; + } + interface ManualRuleGroup { + /** + * The group name, which must be a string. Each group in a given + * ManualRule must have a unique group name. + */ + groupName?: ExtendedValue; + /** + * The items in the source data that should be placed into this group. Each + * item may be a string, number, or boolean. Items may appear in at most one + * group within a given ManualRule. Items that do not appear in any + * group will appear on their own. + */ + items?: ExtendedValue[]; + } interface MatchedDeveloperMetadata { /** All filters matching the returned developer metadata. */ dataFilters?: DataFilter[]; @@ -1589,8 +1726,8 @@ declare namespace gapi.client { /** * Pattern string used for formatting. If not set, a default pattern based on * the user's locale will be used if necessary for the given type. - * See the [Date and Number Formats guide](/sheets/api/guides/formats) for more - * information about the supported patterns. + * See the [Date and Number Formats guide](/sheets/api/guides/formats) for + * more information about the supported patterns. */ pattern?: string; /** @@ -1682,6 +1819,48 @@ declare namespace gapi.client { visibleValues?: string[]; } interface PivotGroup { + /** The group rule to apply to this row/column group. */ + groupRule?: PivotGroupRule; + /** + * The labels to use for the row/column groups which can be customized. For + * example, in the following pivot table, the row label is `Region` (which + * could be renamed to `State`) and the column label is `Product` (which + * could be renamed `Item`). Pivot tables created before December 2017 do + * not have header labels. If you'd like to add header labels to an existing + * pivot table, please delete the existing pivot table and then create a new + * pivot table with same parameters. + * + * +--------------+---------+-------+ + * | SUM of Units | Product | | + * | Region | Pen | Paper | + * +--------------+---------+-------+ + * | New York | 345 | 98 | + * | Oregon | 234 | 123 | + * | Tennessee | 531 | 415 | + * +--------------+---------+-------+ + * | Grand Total | 1110 | 636 | + * +--------------+---------+-------+ + */ + label?: string; + /** + * True if the headings in this pivot group should be repeated. + * This is only valid for row groupings and is ignored by columns. + * + * By default, we minimize repitition of headings by not showing higher + * level headings where they are the same. For example, even though the + * third row below corresponds to "Q1 Mar", "Q1" is not shown because + * it is redundant with previous rows. Setting repeat_headings to true + * would cause "Q1" to be repeated for "Feb" and "Mar". + * + * +--------------+ + * | Q1 | Jan | + * | | Feb | + * | | Mar | + * +--------+-----+ + * | Q1 Total | + * +--------------+ + */ + repeatHeadings?: boolean; /** True if the pivot table should include the totals for this grouping. */ showTotals?: boolean; /** The order the values in this group should be sorted. */ @@ -1702,6 +1881,14 @@ declare namespace gapi.client { /** Metadata about values in the grouping. */ valueMetadata?: PivotGroupValueMetadata[]; } + interface PivotGroupRule { + /** A DateTimeRule. */ + dateTimeRule?: DateTimeRule; + /** A HistogramRule. */ + histogramRule?: HistogramRule; + /** A ManualRule. */ + manualRule?: ManualRule; + } interface PivotGroupSortValueBucket { /** * Determines the bucket from which values are chosen to sort. @@ -1737,7 +1924,7 @@ declare namespace gapi.client { /** * An optional mapping of filters per source column offset. * - * The filters will be applied before aggregating data into the pivot table. + * The filters are applied before aggregating data into the pivot table. * The map's key is the column offset of the source range that you want to * filter, and the value is the criteria for that column. * @@ -1758,15 +1945,21 @@ declare namespace gapi.client { values?: PivotValue[]; } interface PivotValue { + /** + * If specified, indicates that pivot values should be displayed as + * the result of a calculation with another pivot value. For example, if + * calculated_display_type is specified as PERCENT_OF_GRAND_TOTAL, all the + * pivot values are displayed as the percentage of the grand total. In + * the Sheets UI, this is referred to as "Show As" in the value section of a + * pivot table. + */ + calculatedDisplayType?: string; /** * A custom formula to calculate the value. The formula must start * with an `=` character. */ formula?: string; - /** - * A name to use for the value. This is only used if formula was set. - * Otherwise, the column name is used. - */ + /** A name to use for the value. */ name?: string; /** * The column offset of the source range that this value reads from. @@ -1864,6 +2057,8 @@ declare namespace gapi.client { addChart?: AddChartRequest; /** Adds a new conditional format rule. */ addConditionalFormatRule?: AddConditionalFormatRuleRequest; + /** Creates a group over the specified range. */ + addDimensionGroup?: AddDimensionGroupRequest; /** Adds a filter view. */ addFilterView?: AddFilterViewRequest; /** Adds a named range. */ @@ -1899,6 +2094,13 @@ declare namespace gapi.client { deleteDeveloperMetadata?: DeleteDeveloperMetadataRequest; /** Deletes rows or columns in a sheet. */ deleteDimension?: DeleteDimensionRequest; + /** Deletes a group over the specified range. */ + deleteDimensionGroup?: DeleteDimensionGroupRequest; + /** + * Removes rows containing duplicate values in specified columns of a cell + * range. + */ + deleteDuplicates?: DeleteDuplicatesRequest; /** Deletes an embedded object (e.g, chart, image) in a sheet. */ deleteEmbeddedObject?: DeleteEmbeddedObjectRequest; /** Deletes a filter view from a sheet. */ @@ -1939,6 +2141,8 @@ declare namespace gapi.client { sortRange?: SortRangeRequest; /** Converts a column of text into many columns of text. */ textToColumns?: TextToColumnsRequest; + /** Trims cells of whitespace (such as spaces, tabs, or new lines). */ + trimWhitespace?: TrimWhitespaceRequest; /** Unmerges merged cells. */ unmergeCells?: UnmergeCellsRequest; /** Updates a banded range */ @@ -1953,6 +2157,8 @@ declare namespace gapi.client { updateConditionalFormatRule?: UpdateConditionalFormatRuleRequest; /** Updates an existing developer metadata entry */ updateDeveloperMetadata?: UpdateDeveloperMetadataRequest; + /** Updates the state of the specified group. */ + updateDimensionGroup?: UpdateDimensionGroupRequest; /** Updates dimensions' properties. */ updateDimensionProperties?: UpdateDimensionPropertiesRequest; /** Updates an embedded object's (e.g. chart, image) position. */ @@ -1973,6 +2179,8 @@ declare namespace gapi.client { addBanding?: AddBandingResponse; /** A reply from adding a chart. */ addChart?: AddChartResponse; + /** A reply from adding a dimension group. */ + addDimensionGroup?: AddDimensionGroupResponse; /** A reply from adding a filter view. */ addFilterView?: AddFilterViewResponse; /** A reply from adding a named range. */ @@ -1987,12 +2195,18 @@ declare namespace gapi.client { deleteConditionalFormatRule?: DeleteConditionalFormatRuleResponse; /** A reply from deleting a developer metadata entry. */ deleteDeveloperMetadata?: DeleteDeveloperMetadataResponse; + /** A reply from deleting a dimension group. */ + deleteDimensionGroup?: DeleteDimensionGroupResponse; + /** A reply from removing rows containing duplicate values. */ + deleteDuplicates?: DeleteDuplicatesResponse; /** A reply from duplicating a filter view. */ duplicateFilterView?: DuplicateFilterViewResponse; /** A reply from duplicating a sheet. */ duplicateSheet?: DuplicateSheetResponse; /** A reply from doing a find/replace. */ findReplace?: FindReplaceResponse; + /** A reply from trimming whitespace. */ + trimWhitespace?: TrimWhitespaceResponse; /** A reply from updating a conditional format rule. */ updateConditionalFormatRule?: UpdateConditionalFormatRuleResponse; /** A reply from updating a developer metadata entry. */ @@ -2030,12 +2244,17 @@ declare namespace gapi.client { rule?: DataValidationRule; } interface Sheet { - /** The banded (i.e. alternating colors) ranges on this sheet. */ + /** The banded (alternating colors) ranges on this sheet. */ bandedRanges?: BandedRange[]; /** The filter on this sheet, if any. */ basicFilter?: BasicFilter; /** The specifications of every chart on this sheet. */ charts?: EmbeddedChart[]; + /** + * All column groups on this sheet, ordered by increasing range start index, + * then by group depth. + */ + columnGroups?: DimensionGroup[]; /** The conditional format rules in this sheet. */ conditionalFormats?: ConditionalFormatRule[]; /** @@ -2059,6 +2278,11 @@ declare namespace gapi.client { properties?: SheetProperties; /** The protected ranges in this sheet. */ protectedRanges?: ProtectedRange[]; + /** + * All row groups on this sheet, ordered by increasing range start index, then + * by group depth. + */ + rowGroups?: DimensionGroup[]; } interface SheetProperties { /** @@ -2073,12 +2297,12 @@ declare namespace gapi.client { /** * The index of the sheet within the spreadsheet. * When adding or updating sheet properties, if this field - * is excluded then the sheet will be added or moved to the end + * is excluded then the sheet is added or moved to the end * of the sheet list. When updating sheet indices or inserting * sheets, movement is considered in "before the move" indexes. * For example, if there were 3 sheets (S1, S2, S3) in order to * move S1 ahead of S2 the index would have to be set to 2. A sheet - * index update request will be ignored if the requested index is + * index update request is ignored if the requested index is * identical to the sheets current index or if the requested new * index is equal to the current sheet index + 1. */ @@ -2153,9 +2377,8 @@ declare namespace gapi.client { autoRecalc?: string; /** * The default format of all cells in the spreadsheet. - * CellData.effectiveFormat will not be set if the - * cell's format is equal to this default format. - * This field is read-only. + * CellData.effectiveFormat will not be set if + * the cell's format is equal to this default format. This field is read-only. */ defaultFormat?: CellFormat; /** @@ -2217,8 +2440,9 @@ declare namespace gapi.client { * Measured in degrees. Valid values are between -90 and 90. Positive * angles are angled upwards, negative are angled downwards. * - * Note: For LTR text direction positive angles are in the counterclockwise - * direction, whereas for RTL they are in the clockwise direction + * Note: For LTR text direction positive angles are in the + * counterclockwise direction, whereas for RTL they are in the clockwise + * direction */ angle?: number; /** @@ -2248,6 +2472,112 @@ declare namespace gapi.client { /** The source data range. This must span exactly one column. */ source?: GridRange; } + interface TreemapChartColorScale { + /** + * The background color for cells with a color value greater than or equal + * to maxValue. Defaults to #109618 if not + * specified. + */ + maxValueColor?: Color; + /** + * The background color for cells with a color value at the midpoint between + * minValue and + * maxValue. Defaults to #efe6dc if not + * specified. + */ + midValueColor?: Color; + /** + * The background color for cells with a color value less than or equal to + * minValue. Defaults to #dc3912 if not + * specified. + */ + minValueColor?: Color; + /** + * The background color for cells that have no color data associated with + * them. Defaults to #000000 if not specified. + */ + noDataColor?: Color; + } + interface TreemapChartSpec { + /** + * The data that determines the background color of each treemap data cell. + * This field is optional. If not specified, size_data is used to + * determine background colors. If specified, the data is expected to be + * numeric. color_scale will determine how the values in this data map to + * data cell background colors. + */ + colorData?: ChartData; + /** + * The color scale for data cells in the treemap chart. Data cells are + * assigned colors based on their color values. These color values come from + * color_data, or from size_data if color_data is not specified. + * Cells with color values less than or equal to min_value will + * have minValueColor as their + * background color. Cells with color values greater than or equal to + * max_value will have + * maxValueColor as their background + * color. Cells with color values between min_value and max_value will + * have background colors on a gradient between + * minValueColor and + * maxValueColor, the midpoint of + * the gradient being midValueColor. + * Cells with missing or non-numeric color values will have + * noDataColor as their background + * color. + */ + colorScale?: TreemapChartColorScale; + /** The background color for header cells. */ + headerColor?: Color; + /** True to hide tooltips. */ + hideTooltips?: boolean; + /** + * The number of additional data levels beyond the labeled levels to be shown + * on the treemap chart. These levels are not interactive and are shown + * without their labels. Defaults to 0 if not specified. + */ + hintedLevels?: number; + /** The data that contains the treemap cell labels. */ + labels?: ChartData; + /** + * The number of data levels to show on the treemap chart. These levels are + * interactive and are shown with their labels. Defaults to 2 if not + * specified. + */ + levels?: number; + /** + * The maximum possible data value. Cells with values greater than this will + * have the same color as cells with this value. If not specified, defaults + * to the actual maximum value from color_data, or the maximum value from + * size_data if color_data is not specified. + */ + maxValue?: number; + /** + * The minimum possible data value. Cells with values less than this will + * have the same color as cells with this value. If not specified, defaults + * to the actual minimum value from color_data, or the minimum value from + * size_data if color_data is not specified. + */ + minValue?: number; + /** The data the contains the treemap cells' parent labels. */ + parentLabels?: ChartData; + /** + * The data that determines the size of each treemap data cell. This data is + * expected to be numeric. The cells corresponding to non-numeric or missing + * data will not be rendered. If color_data is not specified, this data + * is used to determine data cell background colors as well. + */ + sizeData?: ChartData; + /** The text format for all labels on the chart. */ + textFormat?: TextFormat; + } + interface TrimWhitespaceRequest { + /** The range whose cells to trim. */ + range?: GridRange; + } + interface TrimWhitespaceResponse { + /** The number of cells that were trimmed of whitespace. */ + cellsChangedCount?: number; + } interface UnmergeCellsRequest { /** * The range within which all cells should be unmerged. @@ -2360,6 +2690,19 @@ declare namespace gapi.client { /** The updated developer metadata. */ developerMetadata?: DeveloperMetadata[]; } + interface UpdateDimensionGroupRequest { + /** + * The group whose state should be updated. The range and depth of the group + * should specify a valid group on the sheet, and all other fields updated. + */ + dimensionGroup?: DimensionGroup; + /** + * The fields that should be updated. At least one field must be specified. + * The root `dimensionGroup` is implied and should not be specified. + * A single `"*"` can be used as short-hand for listing every field. + */ + fields?: string; + } interface UpdateDimensionPropertiesRequest { /** * The fields that should be updated. At least one field must be specified. @@ -2523,6 +2866,74 @@ declare namespace gapi.client { */ values?: any[][]; } + interface WaterfallChartColumnStyle { + /** The color of the column. */ + color?: Color; + /** The label of the column's legend. */ + label?: string; + } + interface WaterfallChartCustomSubtotal { + /** + * True if the data point at subtotal_index is the subtotal. If false, + * the subtotal will be computed and appear after the data point. + */ + dataIsSubtotal?: boolean; + /** A label for the subtotal column. */ + label?: string; + /** + * The 0-based index of a data point within the series. If + * data_is_subtotal is true, the data point at this index is the + * subtotal. Otherwise, the subtotal appears after the data point with + * this index. A series can have multiple subtotals at arbitrary indices, + * but subtotals do not affect the indices of the data points. For + * example, if a series has three data points, their indices will always + * be 0, 1, and 2, regardless of how many subtotals exist on the series or + * what data points they are associated with. + */ + subtotalIndex?: number; + } + interface WaterfallChartDomain { + /** The data of the WaterfallChartDomain. */ + data?: ChartData; + /** True to reverse the order of the domain values (horizontal axis). */ + reversed?: boolean; + } + interface WaterfallChartSeries { + /** + * Custom subtotal columns appearing in this series. The order in which + * subtotals are defined is not significant. Only one subtotal may be + * defined for each data point. + */ + customSubtotals?: WaterfallChartCustomSubtotal[]; + /** The data being visualized in this series. */ + data?: ChartData; + /** + * True to hide the subtotal column from the end of the series. By default, + * a subtotal column will appear at the end of each series. Setting this + * field to true will hide that subtotal column for this series. + */ + hideTrailingSubtotal?: boolean; + /** Styles for all columns in this series with negative values. */ + negativeColumnsStyle?: WaterfallChartColumnStyle; + /** Styles for all columns in this series with positive values. */ + positiveColumnsStyle?: WaterfallChartColumnStyle; + /** Styles for all subtotal columns in this series. */ + subtotalColumnsStyle?: WaterfallChartColumnStyle; + } + interface WaterfallChartSpec { + /** The line style for the connector lines. */ + connectorLineStyle?: LineStyle; + /** The domain data (horizontal axis) for the waterfall chart. */ + domain?: WaterfallChartDomain; + /** True to interpret the first value as a total. */ + firstValueIsTotal?: boolean; + /** True to hide connector lines between columns. */ + hideConnectorLines?: boolean; + /** The data this waterfall chart is visualizing. */ + series?: WaterfallChartSeries[]; + /** The stacked type. */ + stackedType?: string; + } interface DeveloperMetadataResource { /** * Returns the developer metadata with the specified ID. @@ -2536,8 +2947,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2548,8 +2957,6 @@ declare namespace gapi.client { metadataId: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2575,8 +2982,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2585,8 +2990,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2597,6 +3000,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: SearchDeveloperMetadataRequest; }): client.Request; } interface SheetsResource { @@ -2611,8 +3016,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2621,8 +3024,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2635,6 +3036,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: CopySheetToAnotherSpreadsheetRequest; }): client.Request; } interface ValuesResource { @@ -2661,8 +3064,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2679,8 +3080,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2710,6 +3109,8 @@ declare namespace gapi.client { upload_protocol?: string; /** How the input data should be interpreted. */ valueInputOption?: string; + /** Request body */ + resource?: ValueRange; }): client.Request; /** * Clears one or more ranges of values from a spreadsheet. @@ -2724,8 +3125,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2734,8 +3133,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2746,6 +3143,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchClearValuesRequest; }): client.Request; /** * Clears one or more ranges of values from a spreadsheet. @@ -2761,8 +3160,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2771,8 +3168,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2783,6 +3178,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchClearValuesByDataFilterRequest; }): client.Request; /** * Returns one or more ranges of values from a spreadsheet. @@ -2795,8 +3192,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** @@ -2822,14 +3217,12 @@ declare namespace gapi.client { majorDimension?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** The A1 notation of the values to retrieve. */ - ranges?: string; + ranges?: string | string[]; /** The ID of the spreadsheet to retrieve data from. */ spreadsheetId: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ @@ -2855,8 +3248,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2865,8 +3256,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2877,6 +3266,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchGetValuesByDataFilterRequest; }): client.Request; /** * Sets values in one or more ranges of a spreadsheet. @@ -2891,8 +3282,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2901,8 +3290,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2913,6 +3300,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchUpdateValuesRequest; }): client.Request; /** * Sets values in one or more ranges of a spreadsheet. @@ -2927,8 +3316,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2937,8 +3324,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2949,6 +3334,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchUpdateValuesByDataFilterRequest; }): client.Request; /** * Clears values from a spreadsheet. @@ -2963,8 +3350,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -2973,8 +3358,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -2987,6 +3370,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: ClearValuesRequest; }): client.Request; /** * Returns a range of values from a spreadsheet. @@ -2999,8 +3384,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** @@ -3026,8 +3409,6 @@ declare namespace gapi.client { majorDimension?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -3058,8 +3439,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -3077,8 +3456,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -3089,7 +3466,8 @@ declare namespace gapi.client { * Determines how dates, times, and durations in the response should be * rendered. This is ignored if response_value_render_option is * FORMATTED_VALUE. - * The default dateTime render option is [DateTimeRenderOption.SERIAL_NUMBER]. + * The default dateTime render option is + * DateTimeRenderOption.SERIAL_NUMBER. */ responseDateTimeRenderOption?: string; /** @@ -3105,6 +3483,8 @@ declare namespace gapi.client { upload_protocol?: string; /** How the input data should be interpreted. */ valueInputOption?: string; + /** Request body */ + resource?: ValueRange; }): client.Request; } interface SpreadsheetsResource { @@ -3136,8 +3516,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -3146,8 +3524,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -3158,6 +3534,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: BatchUpdateSpreadsheetRequest; }): client.Request; /** Creates a spreadsheet, returning the newly created spreadsheet. */ create(request: { @@ -3167,8 +3545,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -3177,8 +3553,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -3187,6 +3561,8 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: Spreadsheet; }): client.Request; /** * Returns the spreadsheet at the given ID. @@ -3218,8 +3594,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -3233,14 +3607,12 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** The ranges to retrieve from the spreadsheet. */ - ranges?: string; + ranges?: string | string[]; /** The spreadsheet to request. */ spreadsheetId: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ @@ -3279,8 +3651,6 @@ declare namespace gapi.client { access_token?: string; /** Data format for response. */ alt?: string; - /** OAuth bearer token. */ - bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ @@ -3289,8 +3659,6 @@ declare namespace gapi.client { key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; - /** Pretty-print response. */ - pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ @@ -3301,10 +3669,14 @@ declare namespace gapi.client { uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; + /** Request body */ + resource?: GetSpreadsheetByDataFilterRequest; }): client.Request; developerMetadata: DeveloperMetadataResource; sheets: SheetsResource; values: ValuesResource; } + + const spreadsheets: SpreadsheetsResource; } } diff --git a/types/gray-percentage/gray-percentage-tests.ts b/types/gray-percentage/gray-percentage-tests.ts new file mode 100644 index 0000000000..e181670a0f --- /dev/null +++ b/types/gray-percentage/gray-percentage-tests.ts @@ -0,0 +1,12 @@ +import grayPercentage = require('gray-percentage'); + +grayPercentage(1); +grayPercentage(1, 1); +grayPercentage(1, 'cool'); +grayPercentage(1, 'slate'); +grayPercentage(1, 'warm'); +grayPercentage(1, 1, true); + +function testReturnValue(value: string): void {} + +testReturnValue(grayPercentage(1)); diff --git a/types/gray-percentage/index.d.ts b/types/gray-percentage/index.d.ts new file mode 100644 index 0000000000..e04ed7e5a9 --- /dev/null +++ b/types/gray-percentage/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for gray-percentage 2.0 +// Project: https://github.com/KyleAMathews/gray-percentage +// Definitions by: Luis Rodrigues +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = grayPercentage; + +declare function grayPercentage( + lightness: number, + hue?: number | 'cool' | 'slate' | 'warm', + darkBackground?: boolean, +): string; diff --git a/types/re2/tsconfig.json b/types/gray-percentage/tsconfig.json similarity index 92% rename from types/re2/tsconfig.json rename to types/gray-percentage/tsconfig.json index 34d96a4c3f..4b03261021 100644 --- a/types/re2/tsconfig.json +++ b/types/gray-percentage/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "re2-tests.ts" + "gray-percentage-tests.ts" ] } diff --git a/types/gray-percentage/tslint.json b/types/gray-percentage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gray-percentage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hdkey/hdkey-tests.ts b/types/hdkey/hdkey-tests.ts index eda1e9e995..977de3768e 100644 --- a/types/hdkey/hdkey-tests.ts +++ b/types/hdkey/hdkey-tests.ts @@ -4,3 +4,5 @@ hdKey.derive('m/1/42'); hdKey.privateKey; hdKey.publicKey; hdKey.chainCode; +hdKey.toJSON(); +HDKey.fromJSON({ xpriv: '', xpub: '' }); diff --git a/types/hdkey/index.d.ts b/types/hdkey/index.d.ts index 3cf798c15b..cc74262a87 100644 --- a/types/hdkey/index.d.ts +++ b/types/hdkey/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for hdkey 0.7 // Project: https://github.com/cryptocoinjs/hdkey // Definitions by: Leonid Logvinov +// Tvrtko Majstorovic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,5 +13,7 @@ declare class HDNode { chainCode: Buffer; constructor(); derive(path: string): HDNode; + toJSON(): { xpriv: string; xpub: string }; + static fromJSON(obj: { xpriv: string; xpub: string }): HDNode; } export = HDNode; diff --git a/types/isstream/index.d.ts b/types/isstream/index.d.ts new file mode 100644 index 0000000000..5ca966f8a6 --- /dev/null +++ b/types/isstream/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for isstream 0.1 +// Project: https://github.com/rvagg/isstream +// Definitions by: Matthew Peveler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isStream(obj: any): boolean; +declare namespace isStream { + function isReadable(obj: any): boolean; + function isWritable(obj: any): boolean; + function isDuplex(obj: any): boolean; +} + +export = isStream; diff --git a/types/isstream/isstream-tests.ts b/types/isstream/isstream-tests.ts new file mode 100644 index 0000000000..d4777058a3 --- /dev/null +++ b/types/isstream/isstream-tests.ts @@ -0,0 +1,42 @@ +/// + +import isStream = require('isstream'); +import { isDuplex, isReadable, isWritable } from 'isstream'; +import { Stream, Readable, Writable, Duplex } from 'stream'; + +const objs = [ + new Stream(), + new Readable(), + new Writable(), + new Duplex(), + 'string', + 10 +]; + +for (let i = 0; i < objs.length; i++) { + let type = 'not a stream'; + if (isStream.isDuplex(objs[i])) { + type = 'duplex'; + } else if (isStream.isWritable(objs[i])) { + type = 'writable'; + } else if (isStream.isReadable(objs[i])) { + type = 'readable'; + } else if (isStream(objs[i])) { + type = 'stream'; + } + console.log(`${i}. ${type}`); +} + +for (let i = 0; i < objs.length; i++) { + let type = 'not a stream'; + if (isDuplex(objs[i])) { + type = 'duplex'; + } else if (isWritable(objs[i])) { + type = 'writable'; + } else if (isReadable(objs[i])) { + type = 'readable'; + } else if (isStream(objs[i])) { + type = 'stream'; + } + console.log(`${i}. ${type}`); +} diff --git a/types/isstream/tsconfig.json b/types/isstream/tsconfig.json new file mode 100644 index 0000000000..03ccf51f8a --- /dev/null +++ b/types/isstream/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "isstream-tests.ts" + ] +} diff --git a/types/isstream/tslint.json b/types/isstream/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/isstream/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/json-rules-engine/index.d.ts b/types/json-rules-engine/index.d.ts index 21ecb66c6a..9102716d3a 100644 --- a/types/json-rules-engine/index.d.ts +++ b/types/json-rules-engine/index.d.ts @@ -78,6 +78,7 @@ export class Rule { | 'equal' | 'notEqual' | 'lessThan' + | 'lessthanInclusive' | 'greaterThan' | 'greaterThanInclusive' | 'in' diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index d898522b9e..04ddab53f3 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2019.2.619 +// Type definitions for Kendo UI Professional v2019.3.917 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1191,6 +1191,13 @@ declare namespace kendo.data { field?: string; dir?: string; aggregates?: DataSourceGroupItemAggregate[]; + compare?: (a: DataSourceGroupCompareItem, b: DataSourceGroupCompareItem) => number; + } + + interface DataSourceGroupCompareItem { + field: string; + value: any; + items: any[]; } interface DataSourceSchema { @@ -1717,7 +1724,7 @@ declare namespace kendo.ui { highlightFirst?: boolean; ignoreCase?: boolean; minLength?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; placeholder?: string; popup?: any; separator?: string|any; @@ -2241,7 +2248,7 @@ declare namespace kendo.ui { ignoreCase?: boolean; index?: number; minLength?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; @@ -2306,8 +2313,7 @@ declare namespace kendo.ui { constructor(element: Element, options?: ConfirmOptions); - - + open(): kendo.ui.Confirm; } interface ConfirmMessages { @@ -2317,7 +2323,11 @@ declare namespace kendo.ui { interface ConfirmOptions { name?: string; + content?: string; messages?: ConfirmMessages; + title?: string | boolean; + initOpen?(e: DialogEvent): void; + open?(e: DialogEvent): void; } interface ConfirmEvent { sender: Confirm; @@ -3014,7 +3024,7 @@ declare namespace kendo.ui { ignoreCase?: boolean; index?: number; minLength?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; popup?: DropDownListPopup; optionLabel?: string|any; optionLabelTemplate?: string|Function; @@ -3160,7 +3170,7 @@ declare namespace kendo.ui { loadOnDemand?: boolean; messages?: DropDownTreeMessages; minLength?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; placeholder?: string; popup?: DropDownTreePopup; headerTemplate?: string|Function; @@ -3595,7 +3605,7 @@ declare namespace kendo.ui { resizable?: boolean | EditorResizable; serialization?: EditorSerialization; stylesheets?: any; - tools?: EditorTool[]; + tools?: EditorTool[]|string[]; imageBrowser?: EditorImageBrowser; fileBrowser?: EditorFileBrowser; change?(e: EditorEvent): void; @@ -3626,6 +3636,112 @@ declare namespace kendo.ui { } + class Filter extends kendo.ui.Widget { + + static fn: Filter; + + options: FilterOptions; + + dataSource: kendo.data.DataSource; + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): Filter; + + constructor(element: Element, options?: FilterOptions); + + + applyFilter(): void; + + } + + interface FilterField { + defaultValue?: any; + editorTemplate?: string|Function; + label?: string; + name?: string; + type?: string; + } + + interface FilterMessages { + and?: string; + apply?: string; + or?: string; + } + + interface FilterOperatorsBoolean { + eq?: string; + neq?: string; + } + + interface FilterOperatorsDate { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterOperatorsNumber { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterOperatorsString { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + isempty?: string; + isnotempty?: string; + startswith?: string; + contains?: string; + doesnotcontain?: string; + endswith?: string; + isnullorempty?: string; + isnotnullorempty?: string; + } + + interface FilterOperators { + string?: FilterOperatorsString; + number?: FilterOperatorsNumber; + date?: FilterOperatorsDate; + boolean?: FilterOperatorsBoolean; + } + + interface FilterOptions { + name?: string; + applyButton?: boolean; + dataSource?: kendo.data.DataSource; + expression?: any; + expressionPreview?: boolean; + fields?: FilterField[]; + mainLogic?: string; + messages?: FilterMessages; + operators?: FilterOperators; + change?(e: FilterChangeEvent): void; + } + interface FilterEvent { + sender: Filter; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface FilterChangeEvent extends FilterEvent { + expression?: any; + } + + class FilterMenu extends kendo.ui.Widget { static fn: FilterMenu; @@ -5279,7 +5395,7 @@ declare namespace kendo.ui { ignoreCase?: boolean; index?: number; minLength?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; placeholder?: string; popup?: MultiColumnComboBoxPopup; suggest?: boolean; @@ -5416,7 +5532,7 @@ declare namespace kendo.ui { ignoreCase?: boolean; minLength?: number; maxSelectedItems?: number; - noDataTemplate?: string|Function; + noDataTemplate?: string|Function|boolean; placeholder?: string; popup?: MultiSelectPopup; headerTemplate?: string|Function; @@ -5966,6 +6082,9 @@ declare namespace kendo.ui { collapse(element: string, useAnimation: boolean): kendo.ui.PanelBar; collapse(element: Element, useAnimation: boolean): kendo.ui.PanelBar; collapse(element: JQuery, useAnimation: boolean): kendo.ui.PanelBar; + dataItem(node: JQuery): kendo.data.Node; + dataItem(node: Element): kendo.data.Node; + dataItem(node: string): kendo.data.Node; destroy(): void; enable(element: string, enable: boolean): void; enable(element: Element, enable: boolean): void; @@ -6317,6 +6436,7 @@ declare namespace kendo.ui { class Popup extends kendo.ui.Widget { static fn: Popup; + static TabKeyTrap: any; options: PopupOptions; @@ -7749,6 +7869,68 @@ declare namespace kendo.ui { checked?: any; } + class Rating extends kendo.ui.Widget { + + static fn: Rating; + + options: RatingOptions; + + + element: JQuery; + wrapper: JQuery; + container: JQuery; + + static extend(proto: Object): Rating; + + constructor(element: Element, options?: RatingOptions); + + value(value: number): void; + reset(): void; + enable(enable: boolean): void; + readonly(enable: boolean): void; + setOptions(options: any): void; + destroy(): void; + } + + interface RatingOptions { + name?: string; + min?: number; + max?: number; + selection: string | "continuous" | "single"; + precision: string | "item" | "half"; + label?: boolean | RatingLabel; + tooltip?: boolean; + itemTemplate?: string|Function; + selectedTemplate?: string|Function; + hoveredTemplate?: string|Function; + selectValueOnFocus?: number; + enabled?: boolean; + readonly?: boolean; + change?(e: RatingChangeEvent): void; + select?(e: RatingSelectEvent): void; + } + + interface RatingLabel { + template: string|Function; + } + + interface RatingEvent { + sender: Rating; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface RatingChangeEvent extends RatingEvent { + target?: Element; + oldValue?: number; + newValue?: number; + } + + interface RatingSelectEvent extends RatingEvent { + target?: Element; + } + + class TabStrip extends kendo.ui.Widget { static fn: TabStrip; @@ -7971,6 +8153,93 @@ declare namespace kendo.ui { interface TimePickerOpenEvent extends TimePickerEvent { } + class Timeline extends kendo.ui.Widget { + + static fn: Timeline; + + options: TimelineOptions; + + dataSource: kendo.data.DataSource; + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): Timeline; + + constructor(element: Element, options?: TimelineOptions); + + + expand(event: string): void; + expand(event: Element): void; + expand(event: JQuery): void; + collapse(event: string): void; + collapse(event: Element): void; + collapse(event: JQuery): void; + open(event: string): void; + open(event: Element): void; + open(event: JQuery): void; + destroy(): void; + next(): void; + previous(): void; + redraw(): void; + setDataSource(dataSource: kendo.data.DataSource): void; + + } + + interface TimelineOptions { + name?: string; + alternatingMode?: boolean; + orientation?: string; + collapsibleEvents?: boolean; + dataActionsField?: string; + dataDescriptionField?: string; + dataDateField?: string; + dataImagesField?: string; + dataSubTitleField?: string; + dataTitleField?: string; + dataSource?: kendo.data.DataSource|any; + eventTemplate?: string|Function; + dateformat?: string; + eventHeight?: number; + eventWidth?: number; + showDateLabels?: boolean; + change?(e: TimelineChangeEvent): void; + dataBound?(e: TimelineDataBoundEvent): void; + expand?(e: TimelineExpandEvent): void; + collapse?(e: TimelineCollapseEvent): void; + actionClick?(e: TimelineActionClickEvent): void; + navigate?(e: TimelineNavigateEvent): void; + } + interface TimelineEvent { + sender: Timeline; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface TimelineChangeEvent extends TimelineEvent { + dataItem?: kendo.data.Model; + eventContainer?: JQuery; + } + + interface TimelineDataBoundEvent extends TimelineEvent { + } + + interface TimelineExpandEvent extends TimelineEvent { + dataItem?: kendo.data.Model; + } + + interface TimelineCollapseEvent extends TimelineEvent { + dataItem?: kendo.data.Model; + } + + interface TimelineActionClickEvent extends TimelineEvent { + dataItem?: kendo.data.Model; + element?: JQuery; + } + + interface TimelineNavigateEvent extends TimelineEvent { + action?: string; + } class ToolBar extends kendo.ui.Widget { @@ -10485,6 +10754,7 @@ declare namespace kendo.dataviz.ui { interface ArcGaugeOptions { name?: string; + centerTemplate?: string|Function; color?: string; colors?: ArcGaugeColor[]; gaugeArea?: ArcGaugeGaugeArea; @@ -21626,6 +21896,10 @@ interface JQuery { kendoEditor(options: kendo.ui.EditorOptions): JQuery; data(key: "kendoEditor"): kendo.ui.Editor; + kendoFilter(): JQuery; + kendoFilter(options: kendo.ui.FilterOptions): JQuery; + data(key: "kendoFilter"): kendo.ui.Filter; + kendoFilterMenu(): JQuery; kendoFilterMenu(options: kendo.ui.FilterMenuOptions): JQuery; data(key: "kendoFilterMenu"): kendo.ui.FilterMenu; @@ -21854,6 +22128,10 @@ interface JQuery { kendoSwitch(options: kendo.ui.SwitchOptions): JQuery; data(key: "kendoSwitch"): kendo.ui.Switch; + kendoRating(): JQuery; + kendoRating(options: kendo.ui.RatingOptions): JQuery; + data(key: "kendoRating"): kendo.ui.Rating; + kendoTabStrip(): JQuery; kendoTabStrip(options: kendo.ui.TabStripOptions): JQuery; data(key: "kendoTabStrip"): kendo.ui.TabStrip; @@ -21862,6 +22140,10 @@ interface JQuery { kendoTimePicker(options: kendo.ui.TimePickerOptions): JQuery; data(key: "kendoTimePicker"): kendo.ui.TimePicker; + kendoTimeline(): JQuery; + kendoTimeline(options: kendo.ui.TimelineOptions): JQuery; + data(key: "kendoTimeline"): kendo.ui.Timeline; + kendoToolBar(): JQuery; kendoToolBar(options: kendo.ui.ToolBarOptions): JQuery; data(key: "kendoToolBar"): kendo.ui.ToolBar; diff --git a/types/libnpmsearch/index.d.ts b/types/libnpmsearch/index.d.ts index 444a8b140e..94c993b8e8 100644 --- a/types/libnpmsearch/index.d.ts +++ b/types/libnpmsearch/index.d.ts @@ -28,9 +28,18 @@ declare namespace search { date?: Date; } + interface Score { + final: number; + detail: { + quality: number; + popularity: number; + maintenance: number; + }; + } + interface DetailedResult { package: Result; - score: number; + score: Score; searchScore: number; } diff --git a/types/lodash/common/object.d.ts b/types/lodash/common/object.d.ts index 90038c4dbc..5bdc326286 100644 --- a/types/lodash/common/object.d.ts +++ b/types/lodash/common/object.d.ts @@ -815,7 +815,7 @@ declare module "../index" { defaults( object: TObject, source: TSource - ): TSource & TObject; + ): NonNullable; /** * @see _.defaults @@ -824,7 +824,7 @@ declare module "../index" { object: TObject, source1: TSource1, source2: TSource2 - ): TSource2 & TSource1 & TObject; + ): NonNullable; /** * @see _.defaults @@ -834,7 +834,7 @@ declare module "../index" { source1: TSource1, source2: TSource2, source3: TSource3 - ): TSource3 & TSource2 & TSource1 & TObject; + ): NonNullable; /** * @see _.defaults @@ -845,12 +845,12 @@ declare module "../index" { source2: TSource2, source3: TSource3, source4: TSource4 - ): TSource4 & TSource3 & TSource2 & TSource1 & TObject; + ): NonNullable; /** * @see _.defaults */ - defaults(object: TObject): TObject; + defaults(object: TObject): NonNullable; /** * @see _.defaults @@ -867,7 +867,7 @@ declare module "../index" { */ defaults( source: TSource - ): LoDashImplicitWrapper; + ): LoDashImplicitWrapper>; /** * @see _.defaults @@ -875,7 +875,7 @@ declare module "../index" { defaults( source1: TSource1, source2: TSource2 - ): LoDashImplicitWrapper; + ): LoDashImplicitWrapper>; /** * @see _.defaults @@ -884,7 +884,7 @@ declare module "../index" { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitWrapper; + ): LoDashImplicitWrapper>; /** * @see _.defaults @@ -894,12 +894,12 @@ declare module "../index" { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitWrapper; + ): LoDashImplicitWrapper>; /** * @see _.defaults */ - defaults(): LoDashImplicitWrapper; + defaults(): LoDashImplicitWrapper>; /** * @see _.defaults @@ -913,7 +913,7 @@ declare module "../index" { */ defaults( source: TSource - ): LoDashExplicitWrapper; + ): LoDashExplicitWrapper>; /** * @see _.defaults @@ -921,7 +921,7 @@ declare module "../index" { defaults( source1: TSource1, source2: TSource2 - ): LoDashExplicitWrapper; + ): LoDashExplicitWrapper>; /** * @see _.defaults @@ -930,7 +930,7 @@ declare module "../index" { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitWrapper; + ): LoDashExplicitWrapper>; /** * @see _.defaults @@ -940,12 +940,12 @@ declare module "../index" { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitWrapper; + ): LoDashExplicitWrapper>; /** * @see _.defaults */ - defaults(): LoDashExplicitWrapper; + defaults(): LoDashExplicitWrapper>; /** * @see _.defaults diff --git a/types/lodash/fp.d.ts b/types/lodash/fp.d.ts index 59f63b4f09..aebe99a611 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -468,16 +468,16 @@ declare namespace _ { interface LodashDefaults { (source: TSource): LodashDefaults1x1; (source: lodash.__, object: TObject): LodashDefaults1x2; - (source: TSource, object: TObject): TSource & TObject; + (source: TSource, object: TObject): NonNullable; } - type LodashDefaults1x1 = (object: TObject) => TSource & TObject; - type LodashDefaults1x2 = (source: TSource) => TSource & TObject; + type LodashDefaults1x1 = (object: TObject) => NonNullable; + type LodashDefaults1x2 = (source: TSource) => NonNullable; interface LodashDefaultsAll { - (object: [TObject, TSource]): TSource & TObject; - (object: [TObject, TSource1, TSource2]): TSource2 & TSource1 & TObject; - (object: [TObject, TSource1, TSource2, TSource3]): TSource3 & TSource2 & TSource1 & TObject; - (object: [TObject, TSource1, TSource2, TSource3, TSource4]): TSource4 & TSource3 & TSource2 & TSource1 & TObject; - (object: [TObject]): TObject; + (object: [TObject, TSource]): NonNullable; + (object: [TObject, TSource1, TSource2]): NonNullable; + (object: [TObject, TSource1, TSource2, TSource3]): NonNullable; + (object: [TObject, TSource1, TSource2, TSource3, TSource4]): NonNullable; + (object: [TObject]): NonNullable; (object: ReadonlyArray): any; } interface LodashDefaultsDeep { diff --git a/types/lodash/ts3.1/common/array.d.ts b/types/lodash/ts3.1/common/array.d.ts index 73e4e642c2..3831ba97ce 100644 --- a/types/lodash/ts3.1/common/array.d.ts +++ b/types/lodash/ts3.1/common/array.d.ts @@ -488,7 +488,9 @@ declare module "../index" { */ flatten(): T extends Many ? CollectionChain : CollectionChain; } - type Flat = (T extends List ? never : T); + + type Flat = T extends string ? T : (T extends List ? never : T); + interface LoDashStatic { /** * Recursively flattens a nested array. diff --git a/types/lodash/ts3.1/common/object.d.ts b/types/lodash/ts3.1/common/object.d.ts index 768accb377..63210e23e6 100644 --- a/types/lodash/ts3.1/common/object.d.ts +++ b/types/lodash/ts3.1/common/object.d.ts @@ -479,23 +479,23 @@ declare module "../index" { * @param sources The source objects. * @return The destination object. */ - defaults(object: TObject, source: TSource): TSource & TObject; + defaults(object: TObject, source: TSource): NonNullable; /** * @see _.defaults */ - defaults(object: TObject, source1: TSource1, source2: TSource2): TSource2 & TSource1 & TObject; + defaults(object: TObject, source1: TSource1, source2: TSource2): NonNullable; /** * @see _.defaults */ - defaults(object: TObject, source1: TSource1, source2: TSource2, source3: TSource3): TSource3 & TSource2 & TSource1 & TObject; + defaults(object: TObject, source1: TSource1, source2: TSource2, source3: TSource3): NonNullable; /** * @see _.defaults */ - defaults(object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): TSource4 & TSource3 & TSource2 & TSource1 & TObject; + defaults(object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): NonNullable; /** * @see _.defaults */ - defaults(object: TObject): TObject; + defaults(object: TObject): NonNullable; /** * @see _.defaults */ @@ -505,23 +505,23 @@ declare module "../index" { /** * @see _.defaults */ - defaults(source: TSource): Object; + defaults(source: TSource): Object>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2): Object; + defaults(source1: TSource1, source2: TSource2): Object>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2, source3: TSource3): Object; + defaults(source1: TSource1, source2: TSource2, source3: TSource3): Object>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): Object; + defaults(source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): Object>; /** * @see _.defaults */ - defaults(): Object; + defaults(): Object>; /** * @see _.defaults */ @@ -531,23 +531,23 @@ declare module "../index" { /** * @see _.defaults */ - defaults(source: TSource): ObjectChain; + defaults(source: TSource): ObjectChain>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2): ObjectChain; + defaults(source1: TSource1, source2: TSource2): ObjectChain>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2, source3: TSource3): ObjectChain; + defaults(source1: TSource1, source2: TSource2, source3: TSource3): ObjectChain>; /** * @see _.defaults */ - defaults(source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): ObjectChain; + defaults(source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4): ObjectChain>; /** * @see _.defaults */ - defaults(): ObjectChain; + defaults(): ObjectChain>; /** * @see _.defaults */ diff --git a/types/lodash/ts3.1/lodash-tests.ts b/types/lodash/ts3.1/lodash-tests.ts index 339f1f2c3e..927a8fae8c 100644 --- a/types/lodash/ts3.1/lodash-tests.ts +++ b/types/lodash/ts3.1/lodash-tests.ts @@ -497,6 +497,9 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType CollectionChain _.flattenDeep([1, [2, [3, [4, 5]]]]); // $ExpectType number[] _.flattenDeep({0: 1, 1: [2, [3, [4, 5]]], length: 2}); // $ExpectType number[] + _.flattenDeep(['x']); // $ExpectType string[] + _.flattenDeep(['x', ['y']]); // $ExpectType string[] + _.flattenDeep([1, 2, 3]); // $ExpectType number[] _.flattenDeep([[1, 2, 3]]); // $ExpectType number[] _.flattenDeep([1, [2, [3, [4, 5]]]]); // $ExpectType number[] diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index c81a4483ea..9a8ab24faf 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Linus Brolin // simonxca // woutgg +// oktapodia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 // @@ -27,7 +28,7 @@ declare module 'mongoose' { customLabels?: CustomLabels; collation?: CollationOptions; /* tslint:disable-next-line: ban-types */ - populate?: Object[] | string[] | Object | string; + populate?: Object[] | string[] | Object | string | QueryPopulateOptions; lean?: boolean; leanWithId?: boolean; offset?: number; @@ -35,6 +36,21 @@ declare module 'mongoose' { limit?: number; } + interface QueryPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: any; + /** optional model to use for population */ + model?: string | Model; + /** optional query options like sort, limit, etc */ + options?: any; + /** deep populate */ + populate?: QueryPopulateOptions | QueryPopulateOptions[]; + } + interface PaginateResult { docs: T[]; total: number; diff --git a/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts index 200ca4e12a..4928b4f008 100644 --- a/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts +++ b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts @@ -43,6 +43,9 @@ router.get('/users.json', (req: Request, res: Response) => { options.sort = { username: (descending ? -1 : 1) }; options.collation = { locale: 'en_US', strength: 1 }; options.populate = ''; + options.populate = { + path: '', + }; options.lean = true; options.leanWithId = false; options.offset = 0; diff --git a/types/mongoose-paginate/index.d.ts b/types/mongoose-paginate/index.d.ts index ad54786f53..6ee5dbc5ce 100644 --- a/types/mongoose-paginate/index.d.ts +++ b/types/mongoose-paginate/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/edwardhotchkiss/mongoose-paginate // Definitions by: Linus Brolin , simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// @@ -10,7 +10,12 @@ declare module 'mongoose' { export interface PaginateOptions { select?: Object | string; sort?: Object | string; - populate?: Array | Array | Object | string; + populate?: + | Array + | Array + | Object + | string + | QueryPopulateOptions; lean?: boolean; leanWithId?: boolean; offset?: number; @@ -18,6 +23,21 @@ declare module 'mongoose' { limit?: number; } + interface QueryPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: any; + /** optional model to use for population */ + model?: string | Model; + /** optional query options like sort, limit, etc */ + options?: any; + /** deep populate */ + populate?: QueryPopulateOptions | QueryPopulateOptions[]; + } + export interface PaginateResult { docs: Array; total: number; diff --git a/types/mongoose-paginate/mongoose-paginate-tests.ts b/types/mongoose-paginate/mongoose-paginate-tests.ts index d55f8a454e..e7a3414dd2 100644 --- a/types/mongoose-paginate/mongoose-paginate-tests.ts +++ b/types/mongoose-paginate/mongoose-paginate-tests.ts @@ -44,6 +44,9 @@ router.get('/users.json', function(req: Request, res: Response) { options.select = 'email username'; options.sort = { 'username': (descending ? -1 : 1) }; options.populate = ''; + options.populate = { + path: '', + }; options.lean = true; options.leanWithId = false; options.offset = 0; diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index f47d3b9c72..842d50b352 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -19,6 +19,64 @@ /// +declare enum ErrorCode { + OTHER_CAUSE = -1, + INTERNAL_SERVER_ERROR = 1, + CONNECTION_FAILED = 100, + OBJECT_NOT_FOUND = 101, + INVALID_QUERY = 102, + INVALID_CLASS_NAME = 103, + MISSING_OBJECT_ID = 104, + INVALID_KEY_NAME = 105, + INVALID_POINTER = 106, + INVALID_JSON = 107, + COMMAND_UNAVAILABLE = 108, + NOT_INITIALIZED = 109, + INCORRECT_TYPE = 111, + INVALID_CHANNEL_NAME = 112, + PUSH_MISCONFIGURED = 115, + OBJECT_TOO_LARGE = 116, + OPERATION_FORBIDDEN = 119, + CACHE_MISS = 120, + INVALID_NESTED_KEY = 121, + INVALID_FILE_NAME = 122, + INVALID_ACL = 123, + TIMEOUT = 124, + INVALID_EMAIL_ADDRESS = 125, + MISSING_CONTENT_TYPE = 126, + MISSING_CONTENT_LENGTH = 127, + INVALID_CONTENT_LENGTH = 128, + FILE_TOO_LARGE = 129, + FILE_SAVE_ERROR = 130, + DUPLICATE_VALUE = 137, + INVALID_ROLE_NAME = 139, + EXCEEDED_QUOTA = 140, + SCRIPT_FAILED = 141, + VALIDATION_ERROR = 142, + INVALID_IMAGE_DATA = 150, + UNSAVED_FILE_ERROR = 151, + INVALID_PUSH_TIME_ERROR = 152, + FILE_DELETE_ERROR = 153, + REQUEST_LIMIT_EXCEEDED = 155, + INVALID_EVENT_NAME = 160, + USERNAME_MISSING = 200, + PASSWORD_MISSING = 201, + USERNAME_TAKEN = 202, + EMAIL_TAKEN = 203, + EMAIL_MISSING = 204, + EMAIL_NOT_FOUND = 205, + SESSION_MISSING = 206, + MUST_CREATE_USER_THROUGH_SIGNUP = 207, + ACCOUNT_ALREADY_LINKED = 208, + INVALID_SESSION_TOKEN = 209, + LINKED_ID_MISSING = 250, + INVALID_LINKED_SESSION = 251, + UNSUPPORTED_SERVICE = 252, + AGGREGATE_ERROR = 600, + FILE_READ_ERROR = 601, + X_DOMAIN_REQUEST = 602 +} + declare namespace Parse { let applicationId: string; @@ -906,76 +964,67 @@ subscription.on('close', () => {}); } } - class Error { + static OTHER_CAUSE: ErrorCode.OTHER_CAUSE; + static INTERNAL_SERVER_ERROR: ErrorCode.INTERNAL_SERVER_ERROR; + static CONNECTION_FAILED: ErrorCode.CONNECTION_FAILED; + static OBJECT_NOT_FOUND: ErrorCode.OBJECT_NOT_FOUND; + static INVALID_QUERY: ErrorCode.INVALID_QUERY; + static INVALID_CLASS_NAME: ErrorCode.INVALID_CLASS_NAME; + static MISSING_OBJECT_ID: ErrorCode.MISSING_OBJECT_ID; + static INVALID_KEY_NAME: ErrorCode.INVALID_KEY_NAME; + static INVALID_POINTER: ErrorCode.INVALID_POINTER; + static INVALID_JSON: ErrorCode.INVALID_JSON; + static COMMAND_UNAVAILABLE: ErrorCode.COMMAND_UNAVAILABLE; + static NOT_INITIALIZED: ErrorCode.NOT_INITIALIZED; + static INCORRECT_TYPE: ErrorCode.INCORRECT_TYPE; + static INVALID_CHANNEL_NAME: ErrorCode.INVALID_CHANNEL_NAME; + static PUSH_MISCONFIGURED: ErrorCode.PUSH_MISCONFIGURED; + static OBJECT_TOO_LARGE: ErrorCode.OBJECT_TOO_LARGE; + static OPERATION_FORBIDDEN: ErrorCode.OPERATION_FORBIDDEN; + static CACHE_MISS: ErrorCode.CACHE_MISS; + static INVALID_NESTED_KEY: ErrorCode.INVALID_NESTED_KEY; + static INVALID_FILE_NAME: ErrorCode.INVALID_FILE_NAME; + static INVALID_ACL: ErrorCode.INVALID_ACL; + static TIMEOUT: ErrorCode.TIMEOUT; + static INVALID_EMAIL_ADDRESS: ErrorCode.INVALID_EMAIL_ADDRESS; + static MISSING_CONTENT_TYPE: ErrorCode.MISSING_CONTENT_TYPE; + static MISSING_CONTENT_LENGTH: ErrorCode.MISSING_CONTENT_LENGTH; + static INVALID_CONTENT_LENGTH: ErrorCode.INVALID_CONTENT_LENGTH; + static FILE_TOO_LARGE: ErrorCode.FILE_TOO_LARGE; + static FILE_SAVE_ERROR: ErrorCode.FILE_SAVE_ERROR; + static DUPLICATE_VALUE: ErrorCode.DUPLICATE_VALUE; + static INVALID_ROLE_NAME: ErrorCode.INVALID_ROLE_NAME; + static EXCEEDED_QUOTA: ErrorCode.EXCEEDED_QUOTA; + static SCRIPT_FAILED: ErrorCode.SCRIPT_FAILED; + static VALIDATION_ERROR: ErrorCode.VALIDATION_ERROR; + static INVALID_IMAGE_DATA: ErrorCode.INVALID_IMAGE_DATA; + static UNSAVED_FILE_ERROR: ErrorCode.UNSAVED_FILE_ERROR; + static INVALID_PUSH_TIME_ERROR: ErrorCode.INVALID_PUSH_TIME_ERROR; + static FILE_DELETE_ERROR: ErrorCode.FILE_DELETE_ERROR; + static REQUEST_LIMIT_EXCEEDED: ErrorCode.REQUEST_LIMIT_EXCEEDED; + static INVALID_EVENT_NAME: ErrorCode.INVALID_EVENT_NAME; + static USERNAME_MISSING: ErrorCode.USERNAME_MISSING; + static PASSWORD_MISSING: ErrorCode.PASSWORD_MISSING; + static USERNAME_TAKEN: ErrorCode.USERNAME_TAKEN; + static EMAIL_TAKEN: ErrorCode.EMAIL_TAKEN; + static EMAIL_MISSING: ErrorCode.EMAIL_MISSING; + static EMAIL_NOT_FOUND: ErrorCode.EMAIL_NOT_FOUND; + static SESSION_MISSING: ErrorCode.SESSION_MISSING; + static MUST_CREATE_USER_THROUGH_SIGNUP: ErrorCode.MUST_CREATE_USER_THROUGH_SIGNUP; + static ACCOUNT_ALREADY_LINKED: ErrorCode.ACCOUNT_ALREADY_LINKED; + static INVALID_SESSION_TOKEN: ErrorCode.INVALID_SESSION_TOKEN; + static LINKED_ID_MISSING: ErrorCode.LINKED_ID_MISSING; + static INVALID_LINKED_SESSION: ErrorCode.INVALID_LINKED_SESSION; + static UNSUPPORTED_SERVICE: ErrorCode.UNSUPPORTED_SERVICE; + static AGGREGATE_ERROR: ErrorCode.AGGREGATE_ERROR; + static FILE_READ_ERROR: ErrorCode.FILE_READ_ERROR; + static X_DOMAIN_REQUEST: ErrorCode.X_DOMAIN_REQUEST; - code: ErrorCode; - message: string; + code: ErrorCode; + message: string; - constructor(code: ErrorCode, message: string); - - } - - /* - * We need to inline the codes in order to make compilation work without this type definition as dependency. - */ - const enum ErrorCode { - - OTHER_CAUSE = -1, - INTERNAL_SERVER_ERROR = 1, - CONNECTION_FAILED = 100, - OBJECT_NOT_FOUND = 101, - INVALID_QUERY = 102, - INVALID_CLASS_NAME = 103, - MISSING_OBJECT_ID = 104, - INVALID_KEY_NAME = 105, - INVALID_POINTER = 106, - INVALID_JSON = 107, - COMMAND_UNAVAILABLE = 108, - NOT_INITIALIZED = 109, - INCORRECT_TYPE = 111, - INVALID_CHANNEL_NAME = 112, - PUSH_MISCONFIGURED = 115, - OBJECT_TOO_LARGE = 116, - OPERATION_FORBIDDEN = 119, - CACHE_MISS = 120, - INVALID_NESTED_KEY = 121, - INVALID_FILE_NAME = 122, - INVALID_ACL = 123, - TIMEOUT = 124, - INVALID_EMAIL_ADDRESS = 125, - MISSING_CONTENT_TYPE = 126, - MISSING_CONTENT_LENGTH = 127, - INVALID_CONTENT_LENGTH = 128, - FILE_TOO_LARGE = 129, - FILE_SAVE_ERROR = 130, - DUPLICATE_VALUE = 137, - INVALID_ROLE_NAME = 139, - EXCEEDED_QUOTA = 140, - SCRIPT_FAILED = 141, - VALIDATION_ERROR = 142, - INVALID_IMAGE_DATA = 150, - UNSAVED_FILE_ERROR = 151, - INVALID_PUSH_TIME_ERROR = 152, - FILE_DELETE_ERROR = 153, - REQUEST_LIMIT_EXCEEDED = 155, - INVALID_EVENT_NAME = 160, - USERNAME_MISSING = 200, - PASSWORD_MISSING = 201, - USERNAME_TAKEN = 202, - EMAIL_TAKEN = 203, - EMAIL_MISSING = 204, - EMAIL_NOT_FOUND = 205, - SESSION_MISSING = 206, - MUST_CREATE_USER_THROUGH_SIGNUP = 207, - ACCOUNT_ALREADY_LINKED = 208, - INVALID_SESSION_TOKEN = 209, - LINKED_ID_MISSING = 250, - INVALID_LINKED_SESSION = 251, - UNSUPPORTED_SERVICE = 252, - AGGREGATE_ERROR = 600, - FILE_READ_ERROR = 601, - X_DOMAIN_REQUEST = 602 + constructor(code: ErrorCode, message: string); } /** diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index fc3def614c..8a04216f1d 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -76,6 +76,16 @@ function test_object() { } +function test_errors() { + try { + throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'sdfds'); + } catch (error) { + if (error.code !== 1) { + console.error('Error code did not match expected number.'); + } + } +} + function test_query() { const gameScore = new GameScore(); diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index b63149544a..07cabb3098 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -19,6 +19,8 @@ declare class Pubnub { static generateUUID(): string; + channelGroups: Pubnub.ChannelGroups; + setUUID(uuid: string): void; getUUID(): string; @@ -31,25 +33,30 @@ declare class Pubnub { publish( params: Pubnub.PublishParameters, - callback: (status: Pubnub.PublishStatus, response: Pubnub.PublishResponse) => void + callback: ( + status: Pubnub.PublishStatus, + response: Pubnub.PublishResponse, + ) => void, ): void; - publish( - params: Pubnub.PublishParameters - ): Promise; + publish(params: Pubnub.PublishParameters): Promise; fire( params: Pubnub.FireParameters, - callback: (status: Pubnub.PublishStatus, response: Pubnub.PublishResponse) => void + callback: ( + status: Pubnub.PublishStatus, + response: Pubnub.PublishResponse, + ) => void, ): void; - fire( - params: Pubnub.FireParameters - ): Promise; + fire(params: Pubnub.FireParameters): Promise; history( params: Pubnub.HistoryParameters, - callback: (status: Pubnub.HistoryStatus, response: Pubnub.HistoryResponse) => void + callback: ( + status: Pubnub.HistoryStatus, + response: Pubnub.HistoryResponse, + ) => void, ): void; subscribe(params: Pubnub.SubscribeParameters): void; @@ -66,48 +73,50 @@ declare class Pubnub { hereNow( params: Pubnub.HereNowParameters, - callback: (status: Pubnub.HereNowStatus, response: Pubnub.HereNowResponse) => void + callback: ( + status: Pubnub.HereNowStatus, + response: Pubnub.HereNowResponse, + ) => void, ): void; - hereNow( - params: Pubnub.HereNowParameters - ): Promise; + hereNow(params: Pubnub.HereNowParameters): Promise; whereNow( params: Pubnub.WhereNowParameters, - callback: (status: Pubnub.WhereNowStatus, response: Pubnub.WhereNowResponse) => void + callback: ( + status: Pubnub.WhereNowStatus, + response: Pubnub.WhereNowResponse, + ) => void, ): void; - whereNow( - params: Pubnub.WhereNowParameters - ): Promise; + whereNow(params: Pubnub.WhereNowParameters): Promise; getState( params: Pubnub.GetStateParameters, - callback: (status: Pubnub.GetStateStatus, state: Pubnub.GetStateResponse) => void + callback: ( + status: Pubnub.GetStateStatus, + state: Pubnub.GetStateResponse, + ) => void, ): void; - getState( - params: Pubnub.GetStateParameters - ): Promise; + getState(params: Pubnub.GetStateParameters): Promise; setState( params: Pubnub.SetStateParameters, - callback: (status: Pubnub.SetStateStatus, state: Pubnub.SetStateResponse) => void + callback: ( + status: Pubnub.SetStateStatus, + state: Pubnub.SetStateResponse, + ) => void, ): void; - setState( - params: Pubnub.SetStateParameters - ): Promise; + setState(params: Pubnub.SetStateParameters): Promise; grant( params: Pubnub.GrantParameters, - callback: (status: Pubnub.GrantStatus, response: {}) => void + callback: (status: Pubnub.GrantStatus, response: {}) => void, ): void; - grant( - params: Pubnub.GrantParameters - ): Promise<{}>; + grant(params: Pubnub.GrantParameters): Promise<{}>; encrypt( data: string, @@ -118,8 +127,10 @@ declare class Pubnub { decrypt( data: string | object, customCipherKey?: string, - options?: Pubnub.CryptoParameters + options?: Pubnub.CryptoParameters, ): any; + + time(): Promise; } declare namespace Pubnub { @@ -269,6 +280,84 @@ declare namespace Pubnub { channelGroups?: string[]; } + // channelGroups + interface ChannelGroups { + addChannels( + params: AddChannelParameters, + callback: (status: ChannelGroupStatus) => void + ): void; + + addChannels( + params: AddChannelParameters + ): Promise<{}>; + + removeChannels( + params: RemoveChannelParameters, + callback: (status: ChannelGroupStatus) => void + ): void; + + removeChannels( + params: RemoveChannelParameters + ): Promise<{}>; + + listChannels( + params: ListChannelsParameters, + callback: (status: ChannelGroupStatus, response: ListChannelsResponse) => void + ): void; + + listChannels( + params: ListChannelsParameters + ): Promise; + + listGroups( + callback: (status: ChannelGroupStatus, response: ListAllGroupsResponse) => void + ): void; + + listGroups(): Promise; + + deleteGroup( + params: DeleteGroupParameters, + callback: (status: ChannelGroupStatus) => void + ): void; + + deleteGroup( + params: DeleteGroupParameters + ): Promise<{}>; + } + + interface AddChannelParameters { + channels: string[]; + channelGroup: string; + } + + interface RemoveChannelParameters { + channels: string[]; + channelGroup: string; + } + + interface ListChannelsParameters { + channelGroup: string; + } + + interface DeleteGroupParameters { + channelGroup: string; + } + + interface ListAllGroupsResponse { + groups: string[]; + } + + interface ListChannelsResponse { + channels: string[]; + } + + interface ChannelGroupStatus { + error: boolean; + errorData?: Error; + operation: string; // see Pubnub.Operations + statusCode?: number; + } + // addListener interface ListenerParameters { status?(statusEvent: StatusEvent): void; @@ -383,6 +472,11 @@ declare namespace Pubnub { mode?: string; } + // fetch time + interface FetchTimeResponse { + timetoken: number; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index eac4d49d24..f384903d2a 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -115,3 +115,48 @@ const mySecret = { pubnub.decrypt(mySecret, undefined, cryptoOptions); pubnub.decrypt('mySecretString', undefined, cryptoOptions); pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); + +pubnub.time().then(response => console.log(response)); + +const channelGroup = 'channel-group-1'; +const channels = ['channel-1']; + +pubnub.channelGroups + .addChannels({ channelGroup, channels }) + .then(response => console.log(response)); + +pubnub.channelGroups + .listChannels({ channelGroup }) + .then(response => console.log(response)); + +pubnub.channelGroups.listGroups().then(response => console.log(response)); + +pubnub.channelGroups + .removeChannels({ channelGroup, channels }) + .then(response => console.log(response)); + +pubnub.channelGroups + .deleteGroup({ channelGroup }) + .then(response => console.log(response)); + +pubnub.channelGroups.addChannels({ channelGroup, channels }, status => + console.log(status), +); + +pubnub.channelGroups.listChannels({ channelGroup }, (status, response) => { + console.log(status); + console.log(response); +}); + +pubnub.channelGroups.listGroups((status, response) => { + console.log(status); + console.log(response); +}); + +pubnub.channelGroups.removeChannels({ channelGroup, channels }, status => + console.log(status), +); + +pubnub.channelGroups.deleteGroup({ channelGroup }, status => + console.log(status), +); diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index e577b7bd7e..4ca5285773 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for puppeteer 1.19 +// Type definitions for puppeteer 1.20 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch // Konstantin Simon Maria Möllers // Simon Schick // Serban Ghita +// Dave Cardwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -220,7 +221,7 @@ export interface Evalable { ): Promise>; } -export interface JSEvalable { +export interface JSEvalable { /** * Evaluates a function in the browser context. * If the function, passed to the frame.evaluate, returns a Promise, then frame.evaluate would wait for the promise to resolve and return its value. @@ -228,7 +229,7 @@ export interface JSEvalable { * @param fn Function to be evaluated in browser context * @param args Arguments to pass to `fn` */ - evaluate( + evaluate>( pageFunction: T, ...args: SerializableOrJSHandle[], ): Promise>; @@ -240,7 +241,7 @@ export interface JSEvalable { * @param args Arguments to pass to `fn` */ evaluateHandle( - pageFunction: (...args: any[]) => any, + pageFunction: (arg1: A, ...args: any[]) => any, ...args: SerializableOrJSHandle[], ): Promise; } @@ -516,7 +517,7 @@ export interface EmulateOptions { userAgent?: string; } -export type EvaluateFn = string | ((...args: any[]) => any); +export type EvaluateFn = string | ((arg1: T, ...args: any[]) => any); export type EvaluateFnReturnType = T extends ((...args: any[]) => infer R) ? R : any; export type LoadEvent = @@ -759,7 +760,7 @@ export interface Worker extends JSEvalable { /** * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. */ -export interface ElementHandle extends JSHandle, Evalable { +export interface ElementHandle extends JSHandle, Evalable { /** * The method runs element.querySelector within the page. * If no element matches the selector, the return value resolve to null. @@ -828,6 +829,14 @@ export interface ElementHandle extends JSHandle, Ev screenshot(options?: Base64ScreenShotOptions): Promise; screenshot(options?: BinaryScreenShotOptions): Promise; screenshot(options?: ScreenshotOptions): Promise; + /** + * Triggers a change and input event once all the provided options have been selected. If there's no has the multiple attribute, all values are considered, otherwise only the first one is taken into account. + * @returns An array of option values that have been successfully selected. + * @since 1.12.0 + */ + select(...values: string[]): Promise; /** * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. * If the element is detached from DOM, the method throws an error. @@ -853,7 +862,7 @@ export interface ExecutionContext extends JSEvalable { } /** JSHandle represents an in-page JavaScript object. */ -export interface JSHandle { +export interface JSHandle extends JSEvalable { /** * Returns a ElementHandle */ diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index e38cafda6c..1fe37c0c91 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -663,3 +663,23 @@ puppeteer.launch().then(async browser => { const isMultiple: boolean = fileChooser.isMultiple(); await fileChooser.accept(['/foo/bar']); }); + +// .evaluate and .evaluateHandle on ElementHandle and JSHandle, and elementHandle.select +(async () => { + const browser = await puppeteer.launch(); + const page = await browser.newPage(); + + const elementHandle = (await page.$('.something')) as puppeteer.ElementHandle; + elementHandle.evaluate(element => { + element; // $ExpectType HTMLDivElement + }); + elementHandle.evaluateHandle(element => { + element; // $ExpectType HTMLDivElement + }); + + const jsHandle = await page.evaluateHandle(() => 'something'); + jsHandle.evaluate(obj => {}); + jsHandle.evaluateHandle(handle => {}); + + const selected: string[] = await elementHandle.select('a', 'b', 'c'); +})(); diff --git a/types/re2/index.d.ts b/types/re2/index.d.ts deleted file mode 100644 index f892b87644..0000000000 --- a/types/re2/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for re2 1.10 -// Project: http://github.com/uhop/node-re2 -// Definitions by: Jamie Magee -// Michael Kriese -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export class RE2 extends RegExp {} diff --git a/types/re2/re2-tests.ts b/types/re2/re2-tests.ts deleted file mode 100644 index 050a2f6495..0000000000 --- a/types/re2/re2-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { RE2 } from 're2'; - -const re = new RE2('\\w+'); -re.test('abc'); - -const Regex = RE2; -const re2 = new Regex('\\s+'); -re2.compile(); diff --git a/types/react-calendar-timeline/index.d.ts b/types/react-calendar-timeline/index.d.ts index cf97e70f50..9591945b64 100644 --- a/types/react-calendar-timeline/index.d.ts +++ b/types/react-calendar-timeline/index.d.ts @@ -1,131 +1,366 @@ -// Type definitions for react-calendar-timeline v0.16.3 +// Type definitions for react-calendar-timeline v0.26.6 // Project: https://github.com/namespace-ee/react-calendar-timeline // Definitions by: Rajab Shakirov // Alex Maclean +// Andrii Los // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.5 -/// +import * as React from 'react'; +import { Moment } from 'moment'; -declare module "react-calendar-timeline" { - - export interface TimelineGroup { - id: number; - title: React.ReactNode; - rightTitle?: React.ReactNode; - } +declare module 'react-calendar-timeline' { + export interface TimelineGroupBase { + id: number; + title: React.ReactNode; + rightTitle?: React.ReactNode; + } - export interface TimelineItem { - id: number; - group: number; - title?: React.ReactNode; - start_time: any; - end_time: any; - canMove?: boolean; - canResize?: boolean | "left" | "right" | "both"; - canChangeGroup?: boolean; - className?: string; - itemProps?: {}; - } + export interface TimelineItemBase { + id: number; + group: number; + title?: React.ReactNode; + start_time: DateType; + end_time: DateType; + canMove?: boolean; + canResize?: boolean | 'left' | 'right' | 'both'; + canChangeGroup?: boolean; + className?: string; + style?: React.CSSProperties; + itemProps?: React.HTMLAttributes; + } - export interface TimelineContext { - visibletimeStart: number, - visibleTimeEnd: number, - timelineWidth: number - } + export type TimelineItem = TimelineItemBase & CustomItemFields; + export type TimelineGroup = TimelineGroupBase & CustomGroupFields; - export interface TimelineTimeSteps { - second: number, - minute: number, - hour: number, - day: number, - month: number, - year: number - } + export interface TimelineContext { + timelineWidth: number; + visibleTimeStart: number; + visibleTimeEnd: number; + canvasTimeStart: number; + canvasTimeEnd: number; + } - export interface TimelineHeaderLabelFormat { - yearShort: string, - yearLong: string, - monthShort: string, - monthMedium: string, - monthMediumLong: string, - monthLong: string, - dayShort: string, - dayLong: string, - hourShort: string, - hourMedium: string, - hourMediumLong: string, - hourLong: string, - time: string - } + export interface ItemContext { + dimensions: { + collisionLeft: number; + collisionWidth: number; + height: number; + isDragging: boolean; + left: number; + order: { + group: { + id: string; + }; + index: number; + }; + originalLeft: number; + stack: boolean; + top: number | null; + width: number; + }; + useResizeHandle: boolean; + title: string; + canMove: boolean; + canResizeLeft: boolean; + canResizeRight: boolean; + selected: boolean; + dragging: boolean; + dragStart: { + x: number; + y: number; + }; + dragTime: number; + dragGroupDelta: number; + resizing: boolean; + resizeEdge: 'left' | 'right'; + resizeStart: number; + resizeTime: number; + width: boolean; + } - export interface ReactCalendarTimelineProps { - groups: TimelineGroup[]; - items: TimelineItem[]; - keys?:{ - groupIdKey: string; - groupTitleKey: string; - itemIdKey: string; - itemTitleKey: string; - itemGroupKey: string; - itemTimeStartKey: string; - itemTimeEndKey: string; - }; - defaultTimeStart?: any; - defaultTimeEnd?: any; - visibleTimeStart?: any; - visibleTimeEnd?: any; - selected?: number[]; - sidebarWidth?: number; - sidebarContent?: React.ReactNode; - rightSidebarWidth?: number; - rightSidebarContent?: React.ReactNode; - dragSnap?: number; - minResizeWidth?: number; - stickyOffset?: number; - stickyHeader?: boolean; - headerRef?: any; - lineHeight?: number; - headerLabelGroupHeight?: number; - headerLabelHeight?: number; - itemHeightRatio?: number; - minZoom?: number; - maxZoom?: number; - clickTolerance?: number; - canMove?: boolean; - canChangeGroup?: boolean; - canResize?: boolean | "left" | "right" | "both"; - useResizeHandle?: boolean; - showCursorLine?: boolean; - stackItems?: boolean; - traditionalZoom?: boolean; - itemTouchSendsClick?: boolean; - timeSteps?: TimelineTimeSteps, - onItemMove?(itemId: number, dragTime: number, newGroupOrder: number): any; - onItemResize?(itemId: number, newResizeEnd: number, edge: "left" | "right"): any; - onItemSelect?(itemId: number, e: any, time: number): any; - onItemClick?(itemId: number, e: any, time: number): any; - onItemDoubleClick?(itemId: number, e: any, time: number): any; - onCanvasClick?(groupId:number, time:number, e:any): any; - onCanvasDoubleClick?(group: TimelineGroup, time: number, e: any): any; - onCanvasContextMenu?(group: TimelineGroup, time: number, e: any): any; - onZoom?(timelineContext: TimelineContext): any; - moveResizeValidator?(action:"move" | "resize", itemId: number, time: number, resizeEdge: "left" | "right"): any; - headerLabelFormats?: TimelineHeaderLabelFormat, - subHeaderLabelFormats?: TimelineHeaderLabelFormat, - onTimeChange?(visibleTimeStart: number, visibleTimeEnd: number, updateScrollCanvas: (start: number, end: number) => void): any; - onTimeInit?(canvasTimeStart: number, canvasTimeEnd: number): any; - onBoundsChange?(canvasTimeStart: number, canvasTimeEnd: number): any; - itemRenderer?: (props: {item: TimelineItem, context: TimelineContext}) => React.ReactElement<{}>; - groupRenderer?: (props: {group: TimelineGroup, isRightSidebar: boolean}) => React.ReactElement<{}>; - minimumWidthForItemContentVisibility?: number; - children?: any; - } + export interface TimeFormat { + long: string; + mediumLong: string; + medium: string; + short: string; + } - export const defaultHeaderLabelFormats: TimelineHeaderLabelFormat; - export const defaultSubHeaderLabelFormats: TimelineHeaderLabelFormat; + export interface LabelFormat { + year: TimeFormat; + month: TimeFormat; + week: TimeFormat; + day: TimeFormat; + hour: TimeFormat; + minute: TimeFormat; + } - let ReactCalendarTimeline : React.ClassicComponentClass; - export default ReactCalendarTimeline; - + export interface ItemRendererGetItemPropsReturnType { + key: number; + ref: React.Ref; + className: string; + onMouseDown: React.MouseEventHandler; + onMouseUp: React.MouseEventHandler; + onTouchStart: React.TouchEventHandler; + onTouchEnd: React.TouchEventHandler; + onDoubleClick: React.MouseEventHandler; + onContextMenu: React.ReactEventHandler; + style: React.CSSProperties; + } + + export type GetItemsProps = Partial>; + + export interface ItemRendererGetResizePropsReturnType { + left?: { + key: number; + ref: React.Ref; + className: string; + }; + right?: { + key: number; + ref: React.Ref; + className: string; + }; + } + + export type GetResizeProps = { + leftStyle?: React.CSSProperties; + rightStyle?: React.CSSProperties; + leftClassName?: string; + rightClassName?: string; + }; + + export interface ReactCalendarItemRendererProps< + CustomItem extends TimelineItemBase = TimelineItemBase + > { + item: CustomItem; + itemContext: ItemContext; + getItemProps: ( + props: GetItemsProps, + ) => { + key: number; + ref: React.Ref; + className: string; + onMouseDown: React.MouseEventHandler; + onMouseUp: React.MouseEventHandler; + onTouchStart: React.TouchEventHandler; + onTouchEnd: React.TouchEventHandler; + onDoubleClick: React.MouseEventHandler; + onContextMenu: React.ReactEventHandler; + style: React.CSSProperties; + }; + getResizeProps: (propsOverride?: GetResizeProps) => ItemRendererGetResizePropsReturnType; + } + + export interface ReactCalendarGroupRendererProps { + group: CustomGroup; + isRightSidebar?: boolean; + } + + export interface OnItemDragObjectBase { + eventType: 'move' | 'resize'; + itemId: number; + time: number; + } + + export interface OnItemDragObjectMove extends OnItemDragObjectBase { + eventType: 'move'; + newGroupOrder: number; + } + + export interface OnItemDragObjectResize extends OnItemDragObjectBase { + eventType: 'resize'; + edge?: 'left' | 'right'; + } + + export interface TimelineKeys { + groupIdKey: string; + groupTitleKey: string; + groupRightTitleKey: string; + itemIdKey: string; + itemTitleKey: string; + itemDivTitleKey: string; + itemGroupKey: string; + itemTimeStartKey: string; + itemTimeEndKey: string; + } + + export interface ReactCalendarTimelineProps< + CustomItem extends TimelineItemBase = TimelineItemBase, + CustomGroup extends TimelineGroupBase = TimelineGroupBase + > { + groups: CustomGroup[]; + items: CustomItem[]; + keys?: TimelineKeys; + defaultTimeStart?: Date | Moment; + defaultTimeEnd?: Date | Moment; + visibleTimeStart?: Date | Moment; + visibleTimeEnd?: Date | Moment; + selected?: number[]; + sidebarWidth?: number; + sidebarContent?: React.ReactNode; + rightSidebarWidth?: number; + rightSidebarContent?: React.ReactNode; + dragSnap?: number; + minResizeWidth?: number; + lineHeight?: number; + itemHeightRatio?: number; + minZoom?: number; + maxZoom?: number; + clickTolerance?: number; + canMove?: boolean; + canChangeGroup?: boolean; + canResize?: false | true | 'left' | 'right' | 'both'; + useResizeHandle?: boolean; + stackItems?: boolean; + traditionalZoom?: boolean; + itemTouchSendsClick?: boolean; + timeSteps?: TimelineTimeSteps; + scrollRef?: React.Ref; + onItemDrag?(itemDragObject: OnItemDragObjectMove | OnItemDragObjectResize): void; + onItemMove?(itemId: number, dragTime: number, newGroupOrder: number): void; + onItemResize?(itemId: number, endTimeOrStartTime: number, edge: 'left' | 'right'): void; + onItemSelect?(itemId: number, e: any, time: number): void; + onItemDeselect?(e: React.SyntheticEvent): void; + onItemClick?(itemId: number, e: React.SyntheticEvent, time: number): void; + onItemDoubleClick?(itemId: number, e: React.SyntheticEvent, time: number): void; + onItemContextMenu?(itemId: number, e: React.SyntheticEvent, time: number): void; + onCanvasClick?(groupId: number, time: number, e: React.SyntheticEvent): void; + onCanvasDoubleClick?(group: CustomGroup, time: number, e: React.SyntheticEvent): void; + onCanvasContextMenu?(group: CustomGroup, time: number, e: React.SyntheticEvent): void; + onZoom?(timelineContext: TimelineContext): void; + moveResizeValidator?( + action: 'move' | 'resize', + itemId: number, + time: number, + resizeEdge: 'left' | 'right', + ): number; + onTimeChange?( + visibleTimeStart: number, + visibleTimeEnd: number, + updateScrollCanvas: (start: number, end: number) => void, + ): any; + onBoundsChange?(canvasTimeStart: number, canvasTimeEnd: number): any; + itemRenderer?: (props: ReactCalendarItemRendererProps) => React.ReactNode; + groupRenderer?: (props: ReactCalendarGroupRendererProps) => React.ReactNode; + resizeDetector?: (containerResizeDetector: any) => void; + verticalLineClassNamesForTime?: (start: number, end: number) => string[] | undefined; + horizontalLineClassNamesForGroup?: (group: CustomGroup) => string[]; + + // Fields that are in propTypes but not documented + headerRef?: React.Ref; + } + + export interface TimelineTimeSteps { + second: number; + minute: number; + hour: number; + day: number; + month: number; + year: number; + } + + export class TimelineMarkers extends React.Component {} + + export interface CustomMarkerChildrenProps { + styles: React.CSSProperties; + date: number; + } + export interface MarkerProps { + date: Date | number; + children?: (props: CustomMarkerChildrenProps) => React.ReactNode; + } + + export class CustomMarker extends React.Component {} + + export interface TodayMarkerProps extends MarkerProps { + interval?: number; + } + export class TodayMarker extends React.Component {} + + export type CursorMarkerProps = Omit; + export class CursorMarker extends React.Component {} + + export class TimelineHeaders extends React.Component> {} + + export interface TimelineHeaderProps { + style?: React.CSSProperties; + className?: string; + calendarHeaderStyle?: React.CSSProperties; + calendarHeaderClassName?: string; + headerRef?: React.Ref; + } + export class TimelineHeader extends React.Component {} + + export interface SidebarHeaderChildrenFnProps { + getRootProps: (propsToOverride?: { style: React.CSSProperties }) => { style: React.CSSProperties }; + data: Data; + } + + export interface SidebarHeaderProps { + variant?: 'left' | 'right'; + headerData?: Data; + children: (props: SidebarHeaderChildrenFnProps) => React.ReactNode; + } + export class SidebarHeader extends React.Component> {} + + export type Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + + export interface IntervalContext { + interval: { startTime: number; endTime: number; labelWidth: number; left: number }; + intervalText: string; + } + export interface GetIntervalProps { + interval?: Interval; + style?: React.CSSProperties; + onClick?: React.MouseEventHandler; + } + export interface IntervalRenderer { + intervalContext: IntervalContext; + getIntervalProps: (props?: GetIntervalProps) => Required & { key: string | number }; + data?: Data; + } + export interface DateHeaderProps { + style?: React.CSSProperties; + className?: string; + unit?: Unit | 'primaryHeader'; + labelFormat?: string | (([startTime, endTime]: [Moment, Moment], unit: Unit, labelWidth: number) => string); + intervalRenderer?: (props?: IntervalRenderer) => React.ReactNode; + headerData?: Data; + children?: (props: SidebarHeaderChildrenFnProps) => React.ReactNode; + height?: number; + } + export class DateHeader extends React.Component> {} + export interface Interval { + startTime: Moment; + endTime: Moment; + } + export interface HeaderContext { + intervals: { startTime: Moment; endTime: Moment }[]; + unit: string; + } + export interface CustomHeaderPropsChildrenFnProps { + timelineContext: TimelineContext; + headerContext: HeaderContext; + getIntervalProps: (props?: GetIntervalProps) => Required & { key: string | number }; + getRootProps: (propsToOverride?: { style: React.CSSProperties }) => { style: React.CSSProperties }; + showPeriod: (startDate: Moment | number, endDate: Moment | number) => void; + data: Data; + } + export interface CustomHeaderProps { + unit?: Unit; + headerData?: Data; + height?: number; + children: (props?: CustomHeaderPropsChildrenFnProps) => React.ReactNode; + } + export class CustomHeader extends React.Component> {} + + export const defaultKeys: TimelineKeys; + export const defaultTimeSteps: TimelineTimeSteps; + export const defaultHeaderFormats: LabelFormat; + + export default class ReactCalendarTimeline< + CustomItem extends TimelineItemBase = TimelineItemBase, + CustomGroup extends TimelineGroupBase = TimelineGroupBase + > extends React.Component> {} } diff --git a/types/react-calendar-timeline/package.json b/types/react-calendar-timeline/package.json new file mode 100644 index 0000000000..44a561e3d0 --- /dev/null +++ b/types/react-calendar-timeline/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": "^2.0.0" + } +} diff --git a/types/react-calendar-timeline/react-calendar-timeline-tests.tsx b/types/react-calendar-timeline/react-calendar-timeline-tests.tsx index 0814bb3afe..3cb986fb35 100644 --- a/types/react-calendar-timeline/react-calendar-timeline-tests.tsx +++ b/types/react-calendar-timeline/react-calendar-timeline-tests.tsx @@ -1,30 +1,314 @@ -import * as React from "react"; -import ReactCalendarTimeline from 'react-calendar-timeline'; -// Don't want to add this as a dependency, because it is only used for tests. -declare const moment: any; +import * as React from 'react'; +import { useState } from 'react'; +import Timeline, { + TimelineGroupBase, + TimelineItemBase, + TimelineItem, + TimelineGroup, + TimelineHeaders, + SidebarHeader, + DateHeader, + CustomHeader, +} from 'react-calendar-timeline'; +import * as moment from 'moment'; +import { Moment } from 'moment'; -const groups = [ - {id: 1, title: 'group 1'}, - {id: 2, title: 'group 2'} -] +const groups1 = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] as TimelineGroupBase[]; -const items = [ - {id: 1, group: 1, title: 'item 1', start_time: moment(), end_time: moment().add(1, 'hour')}, - {id: 2, group: 2, title: 'item 2', start_time: moment().add(-0.5, 'hour'), end_time: moment().add(0.5, 'hour')}, - {id: 3, group: 1, title: 'item 3', start_time: moment().add(2, 'hour'), end_time: moment().add(3, 'hour')} -] +const items1 = [ + { id: 1, group: 1, title: 'item 1', start_time: moment(), end_time: moment().add(1, 'hour') }, + { id: 2, group: 2, title: 'item 2', start_time: moment().add(-0.5, 'hour'), end_time: moment().add(0.5, 'hour') }, + { id: 3, group: 1, title: 'item 3', start_time: moment().add(2, 'hour'), end_time: moment().add(3, 'hour') }, +] as TimelineItemBase[]; class ExampleOfUsingReactCalendarTimeline extends React.Component { - render(){ - return( -
+ render() { + return ( +
Rendered by react! - + > + groups={groups1} + items={items1} + defaultTimeStart={moment().add(-12, 'hour')} + defaultTimeEnd={moment().add(12, 'hour')} + />
- ); + ); } -}; \ No newline at end of file +} + +type TimelineGroupCustom = TimelineGroup<{ data: string }>; +type TimelineItemCustom = TimelineItem<{ data: string }, Moment>; + +const groups2 = [ + { id: 1, title: 'group 1', data: '1' }, + { id: 2, title: 'group 2', data: '1' }, +] as TimelineGroupCustom[]; + +const items2 = [ + { id: 1, group: 1, title: 'item 1', start_time: moment(), end_time: moment().add(1, 'hour'), data: '1' }, + { + id: 2, + group: 2, + title: 'item 2', + start_time: moment().add(-0.5, 'hour'), + end_time: moment().add(0.5, 'hour'), + data: '1', + }, + { + id: 3, + group: 1, + title: 'item 3', + start_time: moment().add(2, 'hour'), + end_time: moment().add(3, 'hour'), + data: '1', + }, +] as TimelineItemCustom[]; + +class ExampleOfUsingReactCalendarTimelineWithCustomGroupAndItemExtension extends React.Component { + render() { + return ( +
+ Rendered by react! + + groups={groups2} + items={items2} + defaultTimeStart={moment().add(-12, 'hour')} + defaultTimeEnd={moment().add(12, 'hour')} + /> +
+ ); + } +} + +const Example: React.FC = () => ( + + + + {({ getRootProps }) => { + return
Left
; + }} +
+ + + + {({ headerContext: { intervals }, getRootProps, getIntervalProps, showPeriod, data }) => { + return ( +
+ {intervals.map(interval => { + const intervalStyle = { + lineHeight: '30px', + textAlign: 'center', + borderLeft: '1px solid black', + cursor: 'pointer', + backgroundColor: 'Turquoise', + color: 'white', + } as React.CSSProperties; + return ( +
{ + showPeriod(interval.startTime, interval.endTime); + }} + {...getIntervalProps({ + interval, + style: intervalStyle, + })} + > +
{interval.startTime.format('YYYY')}
+
+ ); + })} +
+ ); + }} +
+
+
+); + +const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] as TimelineGroupBase[]; + +const items = [ + { id: 1, group: 1, title: 'item 1', start_time: 1, end_time: 1 }, + { id: 2, group: 2, title: 'item 2', start_time: 1, end_time: 1 }, + { id: 3, group: 1, title: 'item 3', start_time: 1, end_time: 1 }, +] as TimelineItemBase[]; + +const defaultTimeStart = moment() + .startOf('day') + .toDate(); +const defaultTimeEnd = moment() + .startOf('day') + .add(1, 'day') + .toDate(); + +const Resize = () => { + const [itemsState, setItems] = useState(items); + + return ( + { + const group = groups[newGroupOrder]; + + setItems( + itemsState.map(item => + item.id === itemId + ? { + ...item, + ...{ + start_time: dragTime, + end_time: dragTime + (item.end_time - item.start_time), + group: group.id, + }, + } + : item, + ), + ); + + console.log('Moved', itemId, dragTime, newGroupOrder); + }} + onItemResize={(itemId, time, edge) => { + setItems( + itemsState.map(item => + item.id === itemId + ? { + ...item, + ...{ + start_time: edge === 'left' ? time : item.start_time, + end_time: edge === 'left' ? item.end_time : time, + }, + } + : item, + ), + ); + + console.log('Resized', itemId, time, edge); + }} + /> + ); +}; + +const TimelineDragTest = () => { + const [itemsState, setItems] = useState(items); + const [draggedItem, setDraggedItem] = useState< + { item: TimelineItemBase; group: TimelineGroupBase; time: number } | undefined + >(undefined); + + return ( + + { + const group = groups[newGroupOrder]; + + setItems( + itemsState.map(item => + item.id === itemId + ? { + ...item, + ...{ + start_time: dragTime, + end_time: dragTime + (item.end_time - item.start_time), + group: group.id, + }, + } + : item, + ), + ); + setDraggedItem(undefined); + console.log('Moved', itemId, dragTime, newGroupOrder); + }} + onItemResize={(itemId, time, edge) => { + setItems( + itemsState.map(item => + item.id === itemId + ? { + ...item, + ...{ + start_time: edge === 'left' ? time : item.start_time, + end_time: edge === 'left' ? item.end_time : time, + }, + } + : item, + ), + ); + setDraggedItem(undefined); + + console.log('Resized', itemId, time, edge); + }} + onItemDrag={itemDragObject => { + if (itemDragObject.eventType === 'move') { + const { itemId, newGroupOrder, time } = itemDragObject; + let item = draggedItem ? draggedItem.item : undefined; + if (!item) { + item = itemsState.find(i => i.id === itemId); + } + setDraggedItem({ item: item, group: groups[newGroupOrder], time }); + } + }} + /> + {draggedItem && ( +
+ {`${moment(draggedItem.time).format('LLL')}, ${draggedItem.group ? draggedItem.group.title : ''}`} +
+ )} +
+ ); +}; + +const Basic: React.FC = () => { + return ( + Above The Left
} + itemTouchSendsClick={false} + stackItems + itemHeightRatio={0.75} + canMove={false} + canResize={false} + defaultTimeStart={defaultTimeStart} + defaultTimeEnd={defaultTimeEnd} + > + + + {({ getRootProps }) => { + return
Left
; + }} +
+ + +
+ + ); +}; diff --git a/types/react-calendar-timeline/tsconfig.json b/types/react-calendar-timeline/tsconfig.json index 0338517fd1..6c69066da1 100644 --- a/types/react-calendar-timeline/tsconfig.json +++ b/types/react-calendar-timeline/tsconfig.json @@ -22,4 +22,4 @@ "index.d.ts", "react-calendar-timeline-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-copy-to-clipboard/index.d.ts b/types/react-copy-to-clipboard/index.d.ts index a09d7bc8be..2327c9610a 100644 --- a/types/react-copy-to-clipboard/index.d.ts +++ b/types/react-copy-to-clipboard/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-copy-to-clipboard 4.2 +// Type definitions for react-copy-to-clipboard 4.3 // Project: https://github.com/nkbt/react-copy-to-clipboard // Definitions by: Meno Abels // Bernabe +// Ward Delabastita // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -13,13 +14,15 @@ export = CopyToClipboard; declare namespace CopyToClipboard { interface Options { - debug: boolean; - message: string; + debug?: boolean; + format?: "text/html" | "text/plain"; + message?: string; } interface Props { + children: React.ReactNode; text: string; - onCopy?(a: string, b: boolean): void; + onCopy?(text: string, result: boolean): void; options?: Options; } } diff --git a/types/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx b/types/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx index c411139501..50e68dc79f 100644 --- a/types/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx +++ b/types/react-copy-to-clipboard/react-copy-to-clipboard-tests.tsx @@ -1,11 +1,22 @@ import * as React from "react"; import CopyToClipboard = require("react-copy-to-clipboard"); -export class Test extends React.Component { +export class OnlyRequiredProps extends React.Component { + render() { + return ( + + + + ); + } +} + +export class AllProps extends React.Component { render() { return ( {}}> + onCopy={() => {}} + options={{debug: true, message: "message", format: "text/plain"}}> Copy to clipboard with span ); diff --git a/types/react-native-modal-filter-picker/index.d.ts b/types/react-native-modal-filter-picker/index.d.ts index 9c0a300318..2fa11904c3 100644 --- a/types/react-native-modal-filter-picker/index.d.ts +++ b/types/react-native-modal-filter-picker/index.d.ts @@ -2,11 +2,20 @@ // Project: https://github.com/hiddentao/react-native-modal-filter-picker#readme // Definitions by: Chang Yanwei // Cheng Gibson +// Zheng Arnaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -import { StyleProp, ViewStyle, TextStyle, KeyboardAvoidingView, ModalProps, ListViewProps } from 'react-native'; +import { + StyleProp, + ViewStyle, + TextStyle, + KeyboardAvoidingView, + ModalProps, + ListViewProps, + FlatListProps, +} from 'react-native'; export interface ModalFilterPickerOption { label: string; @@ -27,7 +36,7 @@ export interface ModalFilterPickerProps { showFilter?: boolean; modal?: ModalProps; selectedOption?: string; - listViewProps?: Partial; + listViewProps?: Partial>; renderOption?: (option: T, isSelected: boolean) => JSX.Element; renderList?: () => JSX.Element; renderCancelButton?: () => JSX.Element; @@ -35,7 +44,7 @@ export interface ModalFilterPickerProps { autoFocus?: boolean; // styling props - overlayStyle?: StyleProp; + overlayStyle?: StyleProp; listContainerStyle?: StyleProp; filterTextInputContainerStyle?: StyleProp; filterTextInputStyle?: StyleProp; diff --git a/types/react-native-privacy-snapshot/index.d.ts b/types/react-native-privacy-snapshot/index.d.ts new file mode 100644 index 0000000000..689b46418c --- /dev/null +++ b/types/react-native-privacy-snapshot/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for react-native-privacy-snapshot 1.0 +// Project: https://github.com/kayla-tech/react-native-privacy-snapshot#readme +// Definitions by: Matthew Bajorek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function enabled(isEnabled: boolean): void; diff --git a/types/react-native-privacy-snapshot/react-native-privacy-snapshot-tests.ts b/types/react-native-privacy-snapshot/react-native-privacy-snapshot-tests.ts new file mode 100644 index 0000000000..e57bc28453 --- /dev/null +++ b/types/react-native-privacy-snapshot/react-native-privacy-snapshot-tests.ts @@ -0,0 +1,4 @@ +import PrivacySnapshot = require('react-native-privacy-snapshot'); + +PrivacySnapshot.enabled(true); +PrivacySnapshot.enabled(false); diff --git a/types/react-native-privacy-snapshot/tsconfig.json b/types/react-native-privacy-snapshot/tsconfig.json new file mode 100644 index 0000000000..93063ffa0c --- /dev/null +++ b/types/react-native-privacy-snapshot/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-privacy-snapshot-tests.ts" + ] +} diff --git a/types/react-native-privacy-snapshot/tslint.json b/types/react-native-privacy-snapshot/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-privacy-snapshot/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index ec0782b3a4..f0b1280e60 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -23,6 +23,7 @@ // Mike Martin // Theo Henry de Villeneuve // Eli White +// Romain Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -8213,6 +8214,10 @@ export namespace Animated { interface LoopAnimationConfig { iterations?: number; // default -1 for infinite + /** + * Defaults to `true` + */ + resetBeforeIteration?: boolean; } /** diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 34af7ec25b..997f045a73 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -16,19 +16,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 -// Known Issue: -// There is a known issue in TypeScript, which doesn't allow decorators to change the signature of the classes -// they are decorating. Due to this, if you are using @connect() decorator in your code, -// you will see a bunch of errors from TypeScript. The current workaround is to use connect() as a function call on -// a separate line instead of as a decorator. Discussed in this github issue: -// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796 - import { Component, - ComponentClass, ComponentType, StatelessComponent, - Context + Context, + NamedExoticComponent } from 'react'; import { @@ -49,7 +42,7 @@ export interface DispatchProp
{ } export type AdvancedComponentDecorator = - (component: ComponentType) => ComponentClass; + (component: ComponentType) => NamedExoticComponent; /** * A property P will be present if: @@ -93,10 +86,10 @@ export type GetProps = C extends ComponentType ? P : never; // Applies LibraryManagedAttributes (proper handling of defaultProps // and propTypes), as well as defines WrappedComponent. -export type ConnectedComponentClass< +export type ConnectedComponent< C extends ComponentType, P -> = ComponentClass> & hoistNonReactStatics.NonReactStatics & { +> = NamedExoticComponent> & hoistNonReactStatics.NonReactStatics & { WrappedComponent: C; }; @@ -106,7 +99,7 @@ export type ConnectedComponentClass< export type InferableComponentEnhancerWithProps = >>>( component: C - ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; + ) => ConnectedComponent, keyof Shared>> & TNeedsProps>; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during @@ -362,7 +355,7 @@ export interface Optionsstate, props, and dispatch into your final props. It makes no * assumptions about defaults or memoization of results, leaving those responsibilities to the caller.It does not - * modify the component class passed to it; instead, it returns a new, connected component class for you to use. + * modify the component class passed to it; instead, it returns a new, connected component for you to use. * * @param selectorFactory The selector factory. See SelectorFactory type for details. * @param connectOptions If specified, further customizes the behavior of the connector. Additionally, any extra diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index 2c26747274..285d46e53c 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -430,15 +430,6 @@ function mapDispatchToProps(dispatch: Dispatch) { }; } -connect( - mapStateToProps, - mapDispatchToProps -)(Counter); - -@connect(mapStateToProps) -class CounterContainer extends React.Component { -} - // Ensure connect's first two arguments can be replaced by wrapper functions interface CounterStateProps { value: number; @@ -621,10 +612,10 @@ const WrappedTestComponent = connect()(TestComponent); // return value of the connect()(TestComponent) is assignable to a ComponentClass // ie: DispatchProp has been removed through decoration -const ADecoratedTestComponent: React.ComponentClass = WrappedTestComponent; +const ADecoratedTestComponent: React.NamedExoticComponent = WrappedTestComponent; ; -const ATestComponent: React.ComponentClass = TestComponent; // $ExpectError +const ATestComponent: React.NamedExoticComponent = TestComponent; // $ExpectError // stateless functions interface HelloMessageProps { @@ -764,7 +755,7 @@ function TestMergedPropsInference() { return { dispatch: 'string' }; } - const ConnectedWithOwnAndState: React.ComponentClass = connect( + const ConnectedWithOwnAndState: React.NamedExoticComponent = connect( mapStateToProps, undefined, (stateProps: StateProps) => ({ @@ -772,7 +763,7 @@ function TestMergedPropsInference() { }), )(MergedPropsComponent); - const ConnectedWithOwnAndDispatch: React.ComponentClass = connect( + const ConnectedWithOwnAndDispatch: React.NamedExoticComponent = connect( undefined, mapDispatchToProps, (stateProps: undefined, dispatchProps: DispatchProps) => ({ @@ -780,7 +771,7 @@ function TestMergedPropsInference() { }), )(MergedPropsComponent); - const ConnectedWithOwn: React.ComponentClass = connect( + const ConnectedWithOwn: React.NamedExoticComponent = connect( undefined, undefined, () => ({ @@ -1450,3 +1441,15 @@ function testConnectedPropsWithStateAndActions() { const ConnectedComponent = connect(Component); } + +function testConnectReturnType() { + const TestComponent: React.FC = () => null; + + const Test = connect()(TestComponent); + + const myHoc1 = (C: React.ComponentClass

): React.ComponentType

=> C; + myHoc1(Test); // $ExpectError + + const myHoc2 = (C: React.FC

): React.ComponentType

=> C; + myHoc2(Test); +} diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 33537aa5fa..b3fade1b23 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -7,919 +7,188 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 -export { ConcreteRequest, GeneratedNode, RequestParameters } from './lib/util/RelayConcreteNode'; export { ConnectionMetadata } from './lib/handlers/connection/RelayConnectionHandler'; export { EdgeRecord, PageInfo } from './lib/handlers/connection/RelayConnectionInterface'; +export { + DeclarativeMutationConfig, + MutationTypes, + RangeBehaviors, + RangeOperations, +} from './lib/mutations/RelayDeclarativeMutationConfig'; +export { + MutationTypes as MutationType, + RangeOperations as RangeOperation, +} from './lib/mutations/RelayDeclarativeMutationConfig'; +export { OptimisticMutationConfig } from './lib/mutations/applyOptimisticMutation'; +export { MutationConfig, MutationParameters } from './lib/mutations/commitMutation'; +export { RelayNetworkLog, LoggerTransactionConfig } from './lib/network/RelayNetworkLoggerTransaction'; +export { + ExecuteFunction, + FetchFunction, + GraphQLResponse, + LogRequestInfoFunction, + Network as INetwork, + PayloadData, + PayloadError, + SubscribeFunction, + Uploadable, + UploadableMap, +} from './lib/network/RelayNetworkTypes'; +export { ObservableFromValue, Observer, Subscribable, Subscription } from './lib/network/RelayObservable'; +export { GraphiQLPrinter, NetworkLogger } from './lib/network/createRelayNetworkLogger'; +export { + GraphQLTaggedNode, + graphql, + getFragment, + getInlineDataFragment, + getPaginationFragment, + getRefetchableFragment, + getRequest, +} from './lib/query/RelayModernGraphQLTag'; +export { + ConnectionEvent, + ConnectionID, + ConnectionReference, + ConnectionReferenceObject, + ConnectionResolver, + ConnectionSnapshot, +} from './lib/store/RelayConnection'; +export { TaskScheduler } from './lib/store/RelayModernQueryExecutor'; +export { RecordState } from './lib/store/RelayRecordState'; +export { + Environment as IEnvironment, + FragmentMap, + FragmentPointer, + FragmentReference, + FragmentSpecResolver, + HandleFieldPayload, + LogEvent, + LogFunction, + Logger, + LoggerProvider, + MissingFieldHandler, + ModuleImportPointer, + NormalizationSelector, + OperationDescriptor, + OperationLoader, + OperationTracker, + OptimisticResponseConfig, + OptimisticUpdate, + OptimisticUpdateFunction, + PluralReaderSelector, + Props, + PublishQueue, + ReaderSelector, + ReadOnlyRecordProxy, + RecordProxy, + RecordSourceProxy, + RecordSourceSelectorProxy, + RelayContext, + RequestDescriptor, + SelectorData, + SelectorStoreUpdater, + SingularReaderSelector, + Snapshot, + StoreUpdater, +} from './lib/store/RelayStoreTypes'; +export { GraphQLSubscriptionConfig } from './lib/subscription/requestSubscription'; +export { + NormalizationArgument, + NormalizationDefer, + NormalizationConnection, + NormalizationField, + NormalizationLinkedField, + NormalizationLinkedHandle, + NormalizationLocalArgumentDefinition, + NormalizationModuleImport, + NormalizationScalarField, + NormalizationSelection, + NormalizationSplitOperation, + NormalizationStream, +} from './lib/util/NormalizationNode'; +export { NormalizationOperation } from './lib/util/NormalizationNode'; export { ReaderArgument, ReaderArgumentDefinition, + ReaderConnection, ReaderField, ReaderFragment, ReaderInlineDataFragment, + ReaderInlineDataFragmentSpread, ReaderLinkedField, + ReaderModuleImport, ReaderPaginationMetadata, ReaderRefetchableFragment, ReaderRefetchMetadata, ReaderScalarField, ReaderSelection, } from './lib/util/ReaderNode'; - -import RelayConcreteNode, { RequestParameters, ConcreteRequest } from './lib/util/RelayConcreteNode'; -import * as ConnectionHandler from './lib/handlers/connection/RelayConnectionHandler'; -import ConnectionInterface from './lib/handlers/connection/RelayConnectionInterface'; - -export { ConnectionHandler, ConnectionInterface, RelayConcreteNode }; - -import { - ReaderFragment, - ReaderSelectableNode, - ReaderPaginationFragment, - ReaderRefetchableFragment, - ReaderField, -} from './lib/util/ReaderNode'; -import { - NormalizationSelectableNode, - NormalizationScalarField, - NormalizationLinkedField, - NormalizationSplitOperation, - NormalizationField, - NormalizationHandle, -} from './lib/util/NormalizationNode'; - -// ./mutations/RelayDeclarativeMutationConfig -interface RangeAddConfig { - type: 'RANGE_ADD'; - parentName?: string; - parentID?: string; - connectionInfo?: ReadonlyArray<{ - key: string; - filters?: Variables; - rangeBehavior: string; - }>; - connectionName?: string; - edgeName: string; - rangeBehaviors?: RangeBehaviors; -} - -interface RangeDeleteConfig { - type: 'RANGE_DELETE'; - parentName?: string; - parentID?: string; - connectionKeys?: ReadonlyArray<{ - key: string; - filters?: Variables; - }>; - connectionName?: string; - deletedIDFieldName: string | ReadonlyArray; - pathToConnection: ReadonlyArray; -} - -interface NodeDeleteConfig { - type: 'NODE_DELETE'; - parentName?: string; - parentID?: string; - connectionName?: string; - deletedIDFieldName: string; -} - -// Unused in Relay Modern -interface LegacyFieldsChangeConfig { - type: 'FIELDS_CHANGE'; - fieldIDs: { [fieldName: string]: DataID | ReadonlyArray }; -} - -// Unused in Relay Modern -interface LegacyRequiredChildrenConfig { - type: 'REQUIRED_CHILDREN'; - children: ReadonlyArray; -} -export type DeclarativeMutationConfig = - | RangeAddConfig - | RangeDeleteConfig - | NodeDeleteConfig - | LegacyFieldsChangeConfig - | LegacyRequiredChildrenConfig; -export type MutationType = 'RANGE_ADD' | 'RANGE_DELETE' | 'NODE_DELETE' | 'FIELDS_CHANGE' | 'REQUIRED_CHILDREN'; -export type RangeOperation = 'append' | 'ignore' | 'prepend' | 'refetch' | 'remove'; -export type RangeBehaviors = - | ((connectionArgs: { [name: string]: unknown }) => RangeOperation) - | { - [key: string]: RangeOperation; - }; - -// ./mutations/applyRelayModernOptimisticMutation -export interface OptimisticMutationConfig { - configs?: ReadonlyArray | null; - mutation: GraphQLTaggedNode; - variables: Variables; - optimisticUpdater?: SelectorStoreUpdater | null; - optimisticResponse?: object; -} - -// ./mutations/commitRelayModernMutation -export interface MutationConfig { - configs?: ReadonlyArray; - mutation: GraphQLTaggedNode; - variables: TOperation['variables']; - uploadables?: UploadableMap; - onCompleted?: - | ((response: TOperation['response'], errors: ReadonlyArray | null | undefined) => void) - | null; - onError?: ((error: Error) => void) | null; - optimisticUpdater?: SelectorStoreUpdater | null; - optimisticResponse?: TOperation['response'] | null; - updater?: SelectorStoreUpdater | null; -} - -// ./lib/network/RelayNetworkLoggerTransaction -export { RelayNetworkLoggerTransaction } from './lib/network/RelayNetworkLoggerTransaction'; - -// ./network/RelayNetworkTypes -export type ExecuteFunction = ( - request: RequestParameters, - variables: Variables, - cacheConfig: CacheConfig, - uploadables?: UploadableMap | null, -) => RelayObservable; - -export type FetchFunction = ( - request: RequestParameters, - variables: Variables, - cacheConfig: CacheConfig, - uploadables?: UploadableMap | null, -) => ObservableFromValue; - -export type GraphQLResponse = - | { - data: PayloadData; - errors?: ReadonlyArray; - extensions?: PayloadExtensions; - } - | { - data?: PayloadData | null; - errors: ReadonlyArray; - extensions?: PayloadExtensions; - }; - -export interface LegacyObserver { - onCompleted?: () => void; - onError?: (error: Error) => void; - onNext?: (data: T) => void; -} - -interface Network { - execute: ExecuteFunction; -} -export { Network as INetwork }; - -export interface PayloadData { - [key: string]: unknown; -} - -export interface PayloadError { - message: string; - locations?: ReadonlyArray<{ - line: number; - column: number; - }>; - severity?: 'CRITICAL' | 'ERROR' | 'WARNING'; // Not officially part of the spec, but used at Facebook -} - -export type SubscribeFunction = ( - request: RequestParameters, - variables: Variables, - cacheConfig: CacheConfig, - observer?: LegacyObserver, -) => RelayObservable | Disposable; - -export type Uploadable = File | Blob; -export interface UploadableMap { - [key: string]: Uploadable; -} - -interface PayloadExtensions { - [key: string]: unknown; -} - -// ./network/RelayObservable -export type ObservableFromValue = Subscribable | Promise | T; - -export interface Observer { - readonly start?: (subscription: Subscription) => void; - readonly next?: (value: T) => void; - readonly error?: (error: Error) => void; - readonly complete?: () => void; - readonly unsubscribe?: (subscription: Subscription) => void; -} - -export interface Subscribable { - subscribe(observer: Observer | Sink): Subscription; -} - -interface Sink { - next(value: T): void; - error(error: Error, isUncaughtThrownError?: boolean): void; - complete(): void; - readonly closed: boolean; -} -type Source = (sink: Sink) => void | Subscription | (() => unknown); - -export interface Subscription { - unsubscribe(): void; - readonly closed: boolean; -} - -// ./lib/network/createRelayNetworkLogger -export { createRelayNetworkLogger } from './lib/network/createRelayNetworkLogger'; - -// ./query/RelayModernGraphQLTag -export type GraphQLTaggedNode = - | ReaderFragment - | ConcreteRequest - | (() => ReaderFragment | ConcreteRequest) - | { - modern: () => ReaderFragment | ConcreteRequest; - }; - -// ./store/RelayRecordState -export type RecordState = 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; - -// ./store/RelayStoreTypes -interface Environment - extends CEnvironment< - Environment, - ReaderFragment, - GraphQLTaggedNode, - ReaderSelectableNode, - NormalizationSelectableNode, - ConcreteRequest, - GraphQLResponse, - OwnedReaderSelector - > { - applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable; - - commitUpdate(updater: StoreUpdater): void; - - commitPayload(operationDescriptor: OperationDescriptor, payload: PayloadData): void; - - getStore(): Store; - - lookup(selector: ReaderSelector, owner?: OperationDescriptor): CSnapshot; - - executeMutation(data: { - operation: OperationDescriptor; - optimisticUpdater?: SelectorStoreUpdater | null; - optimisticResponse?: object | null; - updater?: SelectorStoreUpdater | null; - uploadables?: UploadableMap | null; - }): RelayObservable; -} -export { Environment as IEnvironment }; - -export type FragmentMap = CFragmentMap; - -export type FragmentReference = never & { __tag: 'FragmentReference' }; - -export interface FragmentPointer { - __id: DataID; - __fragments: { [fragmentName: string]: Variables }; - __fragmentOwner: OperationDescriptor | null; -} - -export interface HandleFieldPayload { - readonly args: Variables; - readonly dataID: DataID; - readonly fieldKey: string; - readonly handle: string; - readonly handleKey: string; -} - -export interface MatchPointer { - __id: DataID; - __fragments: { [fragmentName: string]: Variables }; - __fragmentPropName: string; - __module: unknown; -} - -export type MissingFieldHandler = - | { - kind: 'scalar'; - handle: ( - field: NormalizationScalarField, - record: Record | null | undefined, - args: Variables, - store: ReadonlyRecordSourceProxy, - ) => unknown; - } - | { - kind: 'linked'; - handle: ( - field: NormalizationLinkedField, - record: Record | null | undefined, - args: Variables, - store: ReadonlyRecordSourceProxy, - ) => DataID | null | undefined; - } - | { - kind: 'pluralLinked'; - handle: ( - field: NormalizationLinkedField, - record: Record | null | undefined, - args: Variables, - store: ReadonlyRecordSourceProxy, - ) => ReadonlyArray | null | undefined; - }; - -export const RelayDefaultMissingFieldHandlers: ReadonlyArray; - -export interface OperationLoader { - get(reference: unknown): NormalizationSplitOperation | null | undefined; - - load(reference: unknown): Promise; -} - -export type OperationDescriptor = COperationDescriptor< - ReaderSelectableNode, - NormalizationSelectableNode, - ConcreteRequest ->; - -export type OptimisticUpdate = - | { - storeUpdater: StoreUpdater; - } - | { - selectorStoreUpdater: SelectorStoreUpdater | null | undefined; - operation: OperationDescriptor; - response: object | null | undefined; - } - | { - source: RecordSource; - fieldPayloads?: ReadonlyArray | null; - }; - -export interface OwnedReaderSelector { - owner: OperationDescriptor | null; - selector: ReaderSelector; -} - -export interface RecordProxy { - copyFieldsFrom(source: RecordProxy): void; - getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables | null): RecordProxy | null | undefined; - getLinkedRecords( - name: string, - args?: Variables | null, - ): ReadonlyArray | null | undefined; - getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables | null): RecordProxy; - getType(): string; - getValue(name: string, args?: Variables | null): unknown; - setLinkedRecord(record: RecordProxy, name: string, args?: Variables | null): RecordProxy; - setLinkedRecords( - records: Array, - name: string, - args?: Variables | null, - ): RecordProxy; - setValue(value: unknown, name: string, args?: Variables | null): RecordProxy; -} - -export interface RecordSourceProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): RecordProxy | null | undefined; - getRoot(): RecordProxy; -} - -export interface RecordSourceSelectorProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): RecordProxy | null | undefined; - getRoot(): RecordProxy; - getRootField(fieldName: string): RecordProxy | null | undefined; - getPluralRootField(fieldName: string): ReadonlyArray | null | undefined; -} - -export type RelayContext = CRelayContext; - -export type ReaderSelector = CReaderSelector; - -export type NormalizationSelector = CNormalizationSelector; - -export type SelectorStoreUpdater = (store: RecordSourceSelectorProxy, data: TData) => void; - -export type Snapshot = CSnapshot; - -export type StoreUpdater = (store: RecordSourceProxy) => void; - -interface ReadonlyRecordSourceProxy { - get(dataID: DataID): ReadonlyRecordProxy | null | undefined; - getRoot(): ReadonlyRecordProxy; -} - -export interface ReadonlyRecordProxy { - getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables | null): RecordProxy | null | undefined; - getLinkedRecords( - name: string, - args?: Variables | null, - ): ReadonlyArray | null | undefined; - getType(): string; - getValue(name: string, args?: Variables | null): unknown; -} - -interface RecordSource { - get(dataID: DataID): Record | null | undefined; - getRecordIDs(): ReadonlyArray; - getStatus(dataID: DataID): RecordState; - has(dataID: DataID): boolean; - load( - dataID: DataID, - callback: (error: Error | null | undefined, record: Record | null | undefined) => void, - ): void; - size(): number; - toJSON(): Record; -} -export { RecordSource as IRecordSource }; - -interface Store { - getSource(): RecordSource; - check(selector: NormalizationSelector): boolean; - lookup(selector: ReaderSelector, owner?: OperationDescriptor): Snapshot; - notify(): void; - publish(source: RecordSource): void; - retain(selector: NormalizationSelector): Disposable; - subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; - holdGC(): Disposable; -} - -export interface MutableRecordSource extends RecordSource { - clear(): void; - delete(dataID: DataID): void; - remove(dataID: DataID): void; - set(dataID: DataID, record: Record): void; -} - -type Scheduler = (callback: () => void) => void; - -// ./subscription/requestRelaySubscription -export interface GraphQLSubscriptionConfig { - configs?: ReadonlyArray; - subscription: GraphQLTaggedNode; - variables: Variables; - onCompleted?: () => void; - onError?: (error: Error) => void; - onNext?: (response: TSubscriptionPayload | null | undefined) => void; - updater?: SelectorStoreUpdater; -} - -// ./util/RelayCombinedEnvironmentTypes -export interface CEnvironment< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TReaderNode, - TNormalizationNode, - TRequest, - TPayload, - TReaderSelector -> { - check(selector: CNormalizationSelector): boolean; - - lookup( - selector: CReaderSelector, - ): CSnapshot>; - - subscribe( - snapshot: CSnapshot>, - callback: ( - snapshot: CSnapshot>, - ) => void, - ): Disposable; - - retain(selector: CNormalizationSelector): Disposable; - - execute(config: { - operation: COperationDescriptor; - cacheConfig?: CacheConfig | null; - updater?: SelectorStoreUpdater | null; - }): RelayObservable; -} - -export interface CFragmentMap { - [key: string]: TFragment; -} - -export interface CNormalizationSelector { - dataID: DataID; - node: TNormalizationNode; - variables: Variables; -} - -export interface COperationDescriptor { - fragment: CReaderSelector; - node: TRequest; - root: CNormalizationSelector; - variables: Variables; -} - -export interface CReaderSelector { - dataID: DataID; - node: TReaderNode; - variables: Variables; -} - -export interface CRelayContext { - environment: TEnvironment; - variables: Variables; -} - -export interface CSnapshot extends CReaderSelector { - data: SelectorData | null | undefined; - seenRecords: RecordMap; - isMissingData: boolean; - owner: TOwner | null; -} - -export interface FragmentSpecResolver { - /** - * Stop watching for changes to the results of the fragments. - */ - dispose(): void; - - /** - * Get the current results. - */ - resolve(): FragmentSpecResults; - - /** - * Update the resolver with new inputs. Call `resolve()` to get the updated - * results. - */ - setProps(props: Props): void; - - /** - * Override the variables used to read the results of the fragments. Call - * `resolve()` to get the updated results. - */ - setVariables(variables: Variables, request?: ConcreteRequest): void; - - /** - * Subscribe to resolver updates. - * Overrides existing callback (if one has been specified). - */ - setCallback(callback: () => void): void; -} - -export interface FragmentSpecResults { - [key: string]: unknown; -} - -export interface Props { - [key: string]: unknown; -} - -interface RecordMap { - // theoretically, this should be `[dataID: DataID]`, but `DataID` is a string. - [dataID: string]: Record | undefined; -} -export interface SelectorData { - [key: string]: unknown; -} - -// ./util/RelayRuntimeTypes -export interface CacheConfig { - force?: boolean | null; - poll?: number | null; - liveConfigId?: string | null; - metadata?: { [key: string]: unknown }; - transactionId?: string | null; -} - -export type DataID = string; - -export interface Disposable { - dispose(): void; -} - -export interface OperationType { - readonly variables: Variables; - readonly response: unknown; -} - -export interface Variables { - [name: string]: any; -} +export { ConcreteRequest, GeneratedNode, RequestParameters } from './lib/util/RelayConcreteNode'; +export { CacheConfig, DataID, Disposable, OperationType, Variables } from './lib/util/RelayRuntimeTypes'; // Core API +export { RelayModernEnvironment as Environment } from './lib/store/RelayModernEnvironment'; +export { RelayNetwork as Network } from './lib/network/RelayNetwork'; +export { RelayObservable as Observable } from './lib/network/RelayObservable'; +import QueryResponseCache from './lib/network/RelayQueryResponseCache'; +export { QueryResponseCache }; +export { RelayRecordSource as RecordSource } from './lib/store/RelayRecordSource'; +export { RelayModernRecord as Record } from './lib/store/RelayModernRecord'; +export { RelayModernStore as Store } from './lib/store/RelayModernStore'; -// ./RelayModernEnvironment -interface EnvironmentConfig { - readonly configName?: string; - readonly handlerProvider?: HandlerProvider; - readonly operationLoader?: OperationLoader; - readonly network: Network; - readonly store: Store; - readonly missingFieldHandlers?: ReadonlyArray; -} -declare class RelayModernEnvironment implements Environment { - readonly configName: string | null | undefined; - constructor(config: EnvironmentConfig); - getStore(): Store; - getNetwork(): Network; - applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable; - revertUpdate(update: OptimisticUpdate): void; - replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; - applyMutation(data: { - operation: OperationDescriptor; - optimisticUpdater?: SelectorStoreUpdater | null; - optimisticResponse?: object; - }): Disposable; - check(readSelector: NormalizationSelector): boolean; - commitPayload(operationDescriptor: OperationDescriptor, payload: PayloadData): void; - commitUpdate(updater: StoreUpdater): void; - lookup(readSelector: ReaderSelector, owner?: OperationDescriptor): Snapshot; - subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; - retain(selector: NormalizationSelector): Disposable; - execute(data: { - operation: OperationDescriptor; - cacheConfig?: CacheConfig | null; - updater?: SelectorStoreUpdater | null; - }): RelayObservable; - executeMutation({ - operation, - optimisticResponse, - optimisticUpdater, - updater, - uploadables, - }: { - operation: OperationDescriptor; - optimisticUpdater?: SelectorStoreUpdater | null; - optimisticResponse?: object | null; - updater?: SelectorStoreUpdater | null; - uploadables?: UploadableMap | null; - }): RelayObservable; -} -export { RelayModernEnvironment as Environment }; - -type HandlerProvider = (name: string) => Handler | null | undefined; - -// ./network/RelayNetwork -declare const RelayNetwork: { - create(fetchFn: FetchFunction, subscribeFn?: SubscribeFunction): Network; -}; -export { RelayNetwork as Network }; - -// ./network/RelayObservable -declare class RelayObservable implements Subscribable { - // Use RelayObservable.create(source); - private constructor(source: never); - - static create(source: Source): RelayObservable; - - static onUnhandledError(callback: (error: Error, isUncaughtThrownError: boolean) => void): void; - - static from(obj: ObservableFromValue): RelayObservable; - - static fromLegacy( - callback: (observer: LegacyObserver) => Disposable | RelayObservable, - ): RelayObservable; - - catch(fn: (error: Error) => RelayObservable): RelayObservable; - - do(observer: Observer): RelayObservable; - - finally(fn: () => unknown): RelayObservable; - - ifEmpty(alternate: RelayObservable): RelayObservable; - - subscribe(observer: Observer | Sink): Subscription; - - subscribeLegacy(legacyObserver: LegacyObserver): Disposable; - - map(fn: (value: T) => U): RelayObservable; - - mergeMap(fn: (value: T) => ObservableFromValue): RelayObservable; - - poll(pollInterval: number): RelayObservable; - - toPromise(): Promise; -} -export { RelayObservable as Observable }; - -// ./networks/RelayQueryResponseCache -declare class RelayQueryResponseCache { - constructor(config: { size: number; ttl: number }); - clear(): void; - get(queryID: string, variables: Variables): GraphQLResponse | null; - set(queryID: string, variables: Variables, payload: GraphQLResponse): void; -} -export { RelayQueryResponseCache as QueryResponseCache }; - -// ./store/RelayInMemoryRecordSource -declare class RelayInMemoryRecordSource implements MutableRecordSource { - constructor(records?: RecordMap); - clear(): void; - delete(dataID: DataID): void; - get(dataID: DataID): Record | null | undefined; - getRecordIDs(): ReadonlyArray; - getStatus(dataID: DataID): RecordState; - has(dataID: DataID): boolean; - load( - dataID: DataID, - - callback: (error: Error | null | undefined, record: Record | null | undefined) => void, - ): void; - remove(dataID: DataID): void; - set(dataID: DataID, record: Record): void; - size(): number; - toJSON(): Record; -} -export { RelayInMemoryRecordSource as RecordSource }; - -// ./store/RelayModernStore -declare class RelayModernStore implements Store { - constructor(source: MutableRecordSource, gcScheduler?: Scheduler, operationLoader?: OperationLoader | null); - getSource(): RecordSource; - check(selector: NormalizationSelector): boolean; - retain(selector: NormalizationSelector): Disposable; - lookup(selector: ReaderSelector, owner?: OperationDescriptor): Snapshot; - notify(): void; - publish(source: RecordSource): void; - subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; - holdGC(): Disposable; -} -export { RelayModernStore as Store }; - -// ./store/RelayModernSelector via ./store/RelayCore -export function areEqualSelectors(thisSelector: OwnedReaderSelector, thatSelector: OwnedReaderSelector): boolean; - -export function getDataIDsFromObject( - fragments: { [key: string]: ReaderFragment }, - object: { [key: string]: unknown }, -): { [key: string]: DataID | ReadonlyArray | null | undefined }; - -export function getSelector( - operationVariables: Variables, - fragment: ReaderFragment, - item: unknown, -): OwnedReaderSelector | null | undefined; - -export function getSelectorList( - operationVariables: Variables, - fragment: ReaderFragment, - items: ReadonlyArray, -): ReadonlyArray | null | undefined; - -export function getSelectorsFromObject( - operationVariables: Variables, - fragments: { [key: string]: ReaderFragment }, - object: { [key: string]: unknown }, -): { - [key: string]: OwnedReaderSelector | ReadonlyArray | null | undefined; -}; - -export function getVariablesFromObject( - operationVariables: Variables, - fragments: { [key: string]: ReaderFragment }, - object: { [key: string]: unknown }, -): Variables; - -// ./store/RelayModernOperationDescriptor via ./store/RelayCore -export function createOperationDescriptor(request: ConcreteRequest, variables: Variables): OperationDescriptor; - -// ./store/RelayCore -export function createFragmentSpecResolver( - context: RelayContext, - containerName: string, - fragments: FragmentMap, - props: Props, - callback?: () => void, -): FragmentSpecResolver; - -// ./query/RelayModernGraphQLTag -export function getFragment(taggedNode: GraphQLTaggedNode): ReaderFragment; -export function getFragmentOwner( - fragmentNode: ReaderFragment, - fragmentRef: FragmentPointer | ReadonlyArray | null | undefined, -): OperationDescriptor | null; -export function getFragmentOwners( - fragmentNodes: { [key: string]: ReaderFragment }, - fragmentRefs: { - [key: string]: FragmentPointer | ReadonlyArray | null | undefined; - }, -): { [key: string]: OperationDescriptor | null }; -export function getPaginationFragment(taggedNode: GraphQLTaggedNode): ReaderPaginationFragment | null; -export function getRefetchableFragment(taggedNode: GraphQLTaggedNode): ReaderRefetchableFragment | null; -export function getRequest(taggedNode: GraphQLTaggedNode): ConcreteRequest; -export function graphql(strings: ReadonlyArray): GraphQLTaggedNode; - -// ./store/RelayStoreUtils -export function getStorageKey( - field: NormalizationField | NormalizationHandle | ReaderField, - variables: Variables, -): string; -export function getModuleComponentKey(documentName: string): string; -export function getModuleOperationKey(documentName: string): string; - -// Declarative mutation API -// ./mutations/RelayDeclarativeMutationConfig -export const MutationTypes: { - RANGE_ADD: 'RANGE_ADD'; - RANGE_DELETE: 'RANGE_DELETE'; - NODE_DELETE: 'NODE_DELETE'; - FIELDS_CHANGE: 'FIELDS_CHANGE'; - REQUIRED_CHILDREN: 'REQUIRED_CHILDREN'; -}; - -export const RangeOperations: { - APPEND: 'append'; - IGNORE: 'ignore'; - PREPEND: 'prepend'; - REFETCH: 'refetch'; // legacy only - REMOVE: 'remove'; // legacy only -}; - -export const FRAGMENTS_KEY: string; -export const FRAGMENT_OWNER_KEY: string; -export const ID_KEY: string; -export const REF_KEY: string; -export const REFS_KEY: string; -export const ROOT_ID: string; -export const ROOT_TYPE: string; -export const TYPENAME_KEY: string; +export { + areEqualSelectors, + createNormalizationSelector, + createReaderSelector, + getDataIDsFromFragment, + getDataIDsFromObject, + getPluralSelector, + getSelector, + getSelectorsFromObject, + getSingularSelector, + getVariablesFromObject, + getVariablesFromFragment, + getVariablesFromPluralFragment, + getVariablesFromSingularFragment, +} from './lib/store/RelayModernSelector'; +export { createOperationDescriptor, createRequestDescriptor } from './lib/store/RelayModernOperationDescriptor'; +export { + getStorageKey, + getModuleComponentKey, + getModuleOperationKey, + FRAGMENTS_KEY, + FRAGMENT_OWNER_KEY, + ID_KEY, + REF_KEY, + REFS_KEY, + ROOT_ID, + ROOT_TYPE, + TYPENAME_KEY, +} from './lib/store/RelayStoreUtils'; +export { createFragmentSpecResolver } from './lib/store/createFragmentSpecResolver'; // Extensions -// ./handlers/RelayDefaultHandlerProvider -declare function RelayDefaultHandlerProvider(handle: string): Handler; -export { RelayDefaultHandlerProvider as DefaultHandlerProvider }; - -// ./handlers/viewer/RelayViewerHandler -interface RelayViewerHandler { - readonly VIEWER_ID: DataID; - readonly VIEWER_TYPE: 'Viewer'; -} -declare const RelayViewerHandler: RelayViewerHandler; -export { RelayViewerHandler as ViewerHandler }; +export { RelayDefaultHandlerProvider as DefaultHandlerProvider } from './lib/handlers/RelayDefaultHandlerProvider'; +export { + missingViewerFieldHandler as DefaultMissingFieldHandlers, +} from './lib/handlers/RelayDefaultMissingFieldHandlers'; +import * as ConnectionHandler from './lib/handlers/connection/RelayConnectionHandler'; +export { ConnectionHandler }; // Helpers (can be implemented via the above API) - -// ./mutations/applyRelayModernOptimisticMutation -declare function applyRelayModernOptimisticMutation( - environment: Environment, - config: OptimisticMutationConfig, -): Disposable; -export { applyRelayModernOptimisticMutation as applyOptimisticMutation }; - -// ./mutations/commitLocalUpdate -export function commitLocalUpdate(environment: Environment, updater: StoreUpdater): void; - -// ./mutations/commitRelayModernMutation -declare function commitRelayModernMutation( - environment: Environment, - // tslint:disable-next-line no-unnecessary-generics - config: MutationConfig, -): Disposable; -export { commitRelayModernMutation as commitMutation }; - -// ./query/fetchRelayModernQuery -declare function fetchRelayModernQuery( - environment: RelayModernEnvironment, - taggedNode: GraphQLTaggedNode, - variables: T['variables'], - cacheConfig?: CacheConfig | null, -): Promise; -export { fetchRelayModernQuery as fetchQuery }; - -// ./store/isRelayModernEnvironment -export function isRelayModernEnvironment(environment: any): environment is RelayModernEnvironment; - -// ./subscription/requestRelaySubscription -declare function requestRelaySubscription(environment: Environment, config: GraphQLSubscriptionConfig<{}>): Disposable; -export { requestRelaySubscription as requestSubscription }; +export { applyOptimisticMutation } from './lib/mutations/applyOptimisticMutation'; +export { commitLocalUpdate } from './lib/mutations/commitLocalUpdate'; +export { commitMutation } from './lib/mutations/commitMutation'; +export { fetchQuery } from './lib/query/fetchQuery'; +export { isRelayModernEnvironment } from './lib/store/isRelayModernEnvironment'; +export { requestSubscription } from './lib/subscription/requestSubscription'; // Utilities -interface Handler { - update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; -} -type ProfileHandler = (name: string, state?: any) => (error?: Error) => void; -export interface RelayProfiler { - instrumentMethods(object: object, names: { [key: string]: string }): void; - instrument any>(name: string, originalFunction: T): T; - attachAggregateHandler(name: string, handler: Handler): void; - detachAggregateHandler(name: string, handler: Handler): void; - profile(name: string, state?: any): { stop: (error?: Error) => void }; - attachProfileHandler(name: string, handler: ProfileHandler): void; - detachProfileHandler(name: string, handler: ProfileHandler): void; -} -export const RelayProfiler: RelayProfiler; +export { RelayProfiler } from './lib/util/RelayProfiler'; -// Internal API -export function deepFreeze(value: T): T; - -// ./utils/RelayFeatureFlags - -interface FeatureFlags { - ENABLE_VARIABLE_CONNECTION_KEY: boolean; -} - -export const RelayFeatureFlags: FeatureFlags; +// INTERNAL-ONLY +export { RelayConcreteNode } from './lib/util/RelayConcreteNode'; +export { RelayFeatureFlags } from './lib/util/RelayFeatureFlags'; +export { RelayNetworkLoggerTransaction } from './lib/network/RelayNetworkLoggerTransaction'; +export { createRelayNetworkLogger } from './lib/network/createRelayNetworkLogger'; +export { deepFreeze } from './lib/util/deepFreeze'; diff --git a/types/relay-runtime/lib/handlers/RelayDefaultHandlerProvider.d.ts b/types/relay-runtime/lib/handlers/RelayDefaultHandlerProvider.d.ts new file mode 100644 index 0000000000..88a36e28c6 --- /dev/null +++ b/types/relay-runtime/lib/handlers/RelayDefaultHandlerProvider.d.ts @@ -0,0 +1,5 @@ +import { Handler } from '../store/RelayStoreTypes'; + +export type HandlerProvider = (handle: string) => any; + +export function RelayDefaultHandlerProvider(handle: string): Handler; diff --git a/types/relay-runtime/lib/handlers/RelayDefaultMissingFieldHandlers.d.ts b/types/relay-runtime/lib/handlers/RelayDefaultMissingFieldHandlers.d.ts new file mode 100644 index 0000000000..7ce4239b73 --- /dev/null +++ b/types/relay-runtime/lib/handlers/RelayDefaultMissingFieldHandlers.d.ts @@ -0,0 +1,3 @@ +import { MissingFieldHandler } from '../store/RelayStoreTypes'; + +export const missingViewerFieldHandler: MissingFieldHandler; diff --git a/types/relay-runtime/lib/handlers/connection/RelayConnectionHandler.d.ts b/types/relay-runtime/lib/handlers/connection/RelayConnectionHandler.d.ts index eea5e9f437..dba1e49076 100644 --- a/types/relay-runtime/lib/handlers/connection/RelayConnectionHandler.d.ts +++ b/types/relay-runtime/lib/handlers/connection/RelayConnectionHandler.d.ts @@ -1,11 +1,10 @@ +import { DataID, Variables } from '../../../lib/util/RelayRuntimeTypes'; import { - DataID, RecordSourceProxy, RecordProxy, - Variables, + ReadOnlyRecordProxy, HandleFieldPayload, - ReadonlyRecordProxy, -} from '../../../index'; +} from '../../../lib/store/RelayStoreTypes'; export interface ConnectionMetadata { path: ReadonlyArray | null | undefined; @@ -30,7 +29,7 @@ export function createEdge( export function deleteNode(record: RecordProxy, nodeID: DataID): void; export function getConnection( - record: ReadonlyRecordProxy, + record: ReadOnlyRecordProxy, key: string, filters?: Variables | null, ): RecordProxy | null | undefined; diff --git a/types/relay-runtime/lib/handlers/connection/RelayConnectionInterface.d.ts b/types/relay-runtime/lib/handlers/connection/RelayConnectionInterface.d.ts index 99866eefbb..ed9613b143 100644 --- a/types/relay-runtime/lib/handlers/connection/RelayConnectionInterface.d.ts +++ b/types/relay-runtime/lib/handlers/connection/RelayConnectionInterface.d.ts @@ -1,4 +1,4 @@ -import { DataID } from '../../../index'; +import { DataID } from '../../../lib/util/RelayRuntimeTypes'; export interface EdgeRecord extends Record { cursor: unknown; diff --git a/types/relay-runtime/lib/mutations/RelayDeclarativeMutationConfig.d.ts b/types/relay-runtime/lib/mutations/RelayDeclarativeMutationConfig.d.ts new file mode 100644 index 0000000000..69fd36df57 --- /dev/null +++ b/types/relay-runtime/lib/mutations/RelayDeclarativeMutationConfig.d.ts @@ -0,0 +1,59 @@ +import { Variables } from '../util/RelayRuntimeTypes'; +import { ConcreteRequest } from '../util/RelayConcreteNode'; +import { SelectorStoreUpdater } from '../store/RelayStoreTypes'; + +export type MutationTypes = 'RANGE_ADD' | 'RANGE_DELETE' | 'NODE_DELETE'; + +export type RangeOperations = 'append' | 'prepend'; +export type RangeBehaviorsFunction = (connectionArgs: { [name: string]: unknown }) => RangeOperations; +export interface RangeBehaviorsObject { + [key: string]: RangeOperations; +} +export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; + +export interface RangeAddConfig { + type: 'RANGE_ADD'; + parentName?: string; + parentID?: string; + connectionInfo?: ReadonlyArray<{ + key: string; + filters?: Variables; + rangeBehavior: string; + }>; + connectionName?: string; + edgeName: string; + rangeBehaviors?: RangeBehaviors; +} + +export interface RangeDeleteConfig { + type: 'RANGE_DELETE'; + parentName?: string; + parentID?: string; + connectionKeys?: ReadonlyArray<{ + key: string; + filters?: Variables; + }>; + connectionName?: string; + deletedIDFieldName: string | ReadonlyArray; + pathToConnection: ReadonlyArray; +} + +export interface NodeDeleteConfig { + type: 'NODE_DELETE'; + parentName?: string; + parentID?: string; + connectionName?: string; + deletedIDFieldName: string; +} + +export type DeclarativeMutationConfig = RangeAddConfig | RangeDeleteConfig | NodeDeleteConfig; + +export function convert( + configs: DeclarativeMutationConfig[], + request: ConcreteRequest, + optimisticUpdater?: SelectorStoreUpdater, + updater?: SelectorStoreUpdater, +): { + optimisticUpdater: SelectorStoreUpdater; + updater: SelectorStoreUpdater; +}; diff --git a/types/relay-runtime/lib/mutations/applyOptimisticMutation.d.ts b/types/relay-runtime/lib/mutations/applyOptimisticMutation.d.ts new file mode 100644 index 0000000000..732a0c5c39 --- /dev/null +++ b/types/relay-runtime/lib/mutations/applyOptimisticMutation.d.ts @@ -0,0 +1,18 @@ +import { DeclarativeMutationConfig } from './RelayDeclarativeMutationConfig'; +import { Disposable, Variables } from '../util/RelayRuntimeTypes'; +import { GraphQLTaggedNode } from '../query/RelayModernGraphQLTag'; +import { SelectorStoreUpdater, Environment } from '../store/RelayStoreTypes'; + +export interface OptimisticMutationConfig { + configs?: ReadonlyArray | null; + mutation: GraphQLTaggedNode; + variables: Variables; + optimisticUpdater?: SelectorStoreUpdater | null; + optimisticResponse?: object; +} + +/** + * Higher-level helper function to execute a mutation against a specific + * environment. + */ +export function applyOptimisticMutation(environment: Environment, config: OptimisticMutationConfig): Disposable; diff --git a/types/relay-runtime/lib/mutations/commitLocalUpdate.d.ts b/types/relay-runtime/lib/mutations/commitLocalUpdate.d.ts new file mode 100644 index 0000000000..7c3b02b828 --- /dev/null +++ b/types/relay-runtime/lib/mutations/commitLocalUpdate.d.ts @@ -0,0 +1,3 @@ +import { Environment, StoreUpdater } from '../store/RelayStoreTypes'; + +export function commitLocalUpdate(environment: Environment, updater: StoreUpdater): void; diff --git a/types/relay-runtime/lib/mutations/commitMutation.d.ts b/types/relay-runtime/lib/mutations/commitMutation.d.ts new file mode 100644 index 0000000000..beab50edc9 --- /dev/null +++ b/types/relay-runtime/lib/mutations/commitMutation.d.ts @@ -0,0 +1,36 @@ +import { PayloadError, UploadableMap } from '../network/RelayNetworkTypes'; +import { Disposable, Variables } from '../util/RelayRuntimeTypes'; +import { DeclarativeMutationConfig } from './RelayDeclarativeMutationConfig'; +import { GraphQLTaggedNode } from '../query/RelayModernGraphQLTag'; +import { SelectorStoreUpdater } from '../store/RelayStoreTypes'; +import { RelayModernEnvironment as Environment } from '../store/RelayModernEnvironment'; + +export interface MutationParameters { + readonly variables: Variables; + readonly response: unknown; + readonly rawResponse?: unknown; +} + +export interface MutationConfig { + configs?: ReadonlyArray; + mutation: GraphQLTaggedNode; + variables: TOperation['variables']; + uploadables?: UploadableMap; + onCompleted?: + | ((response: TOperation['response'], errors: ReadonlyArray | null | undefined) => void) + | null; + onError?: ((error: Error) => void) | null; + optimisticUpdater?: SelectorStoreUpdater | null; + optimisticResponse?: TOperation['response'] | null; + updater?: SelectorStoreUpdater | null; +} + +/** + * Higher-level helper function to execute a mutation against a specific + * environment. + */ +export function commitMutation( + environment: Environment, + // tslint:disable-next-line no-unnecessary-generics + config: MutationConfig, +): Disposable; diff --git a/types/relay-runtime/lib/network/RelayNetwork.d.ts b/types/relay-runtime/lib/network/RelayNetwork.d.ts new file mode 100644 index 0000000000..66a1d772f0 --- /dev/null +++ b/types/relay-runtime/lib/network/RelayNetwork.d.ts @@ -0,0 +1,5 @@ +import { FetchFunction, SubscribeFunction, Network } from './RelayNetworkTypes'; + +export const RelayNetwork: { + create(fetchFn: FetchFunction, subscribeFn?: SubscribeFunction): Network; +}; diff --git a/types/relay-runtime/lib/network/RelayNetworkLoggerTransaction.d.ts b/types/relay-runtime/lib/network/RelayNetworkLoggerTransaction.d.ts index 13c77f6f93..03db1f0127 100644 --- a/types/relay-runtime/lib/network/RelayNetworkLoggerTransaction.d.ts +++ b/types/relay-runtime/lib/network/RelayNetworkLoggerTransaction.d.ts @@ -1,5 +1,6 @@ import { RequestParameters } from '../util/RelayConcreteNode'; -import { Variables, CacheConfig, UploadableMap, GraphQLResponse } from '../../index'; +import { Variables, CacheConfig } from '../util/RelayRuntimeTypes'; +import { UploadableMap, GraphQLResponse } from './RelayNetworkTypes'; export interface RelayNetworkLog { label: string; diff --git a/types/relay-runtime/lib/network/RelayNetworkTypes.d.ts b/types/relay-runtime/lib/network/RelayNetworkTypes.d.ts new file mode 100644 index 0000000000..3078c4699c --- /dev/null +++ b/types/relay-runtime/lib/network/RelayNetworkTypes.d.ts @@ -0,0 +1,95 @@ +import { RequestParameters } from '../util/RelayConcreteNode'; +import { Variables, CacheConfig, Disposable } from '../util/RelayRuntimeTypes'; +import { ObservableFromValue, RelayObservable } from './RelayObservable'; + +/** + * An interface for fetching the data for one or more (possibly interdependent) + * queries. + */ +export interface Network { + execute: ExecuteFunction; +} +export type LogRequestInfoFunction = (arg: any) => void; + +export interface PayloadData { + [key: string]: any; +} + +export interface PayloadError { + message: string; + locations?: Array<{ + line: number; + column: number; + }>; + severity?: 'CRITICAL' | 'ERROR' | 'WARNING'; // Not officially part of the spec, but used at Facebook +} + +export interface PayloadExtensions { + [key: string]: any; +} + +/** + * The shape of a GraphQL response as dictated by the + * [spec](https://graphql.github.io/graphql-spec/June2018/#sec-Response-Format) + */ +export interface GraphQLResponseWithData { + data: PayloadData; + errors?: PayloadError[]; + extensions?: PayloadExtensions; + label?: string; + path?: string[] | number[]; +} +export interface GraphQLResponseWithoutData { + data?: PayloadData; + errors: PayloadError[]; + extensions?: PayloadExtensions; + label?: string; + path?: Array; +} +export type GraphQLResponse = GraphQLResponseWithData | GraphQLResponseWithoutData; + +/** + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ +export type ExecuteFunction = ( + request: RequestParameters, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: UploadableMap | null, +) => RelayObservable; + +/** + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a plain GraphQL server response, or + * a composed ExecutePayload object supporting additional metadata. + */ +export type FetchFunction = ( + request: RequestParameters, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: UploadableMap | null, +) => ObservableFromValue; + +export interface LegacyObserver { + onCompleted?: () => void; + onError?: (error: Error) => void; + onNext?: (data: T) => void; +} + +/** + * A function that executes a GraphQL subscription operation, returning zero or + * more raw server responses over time. + */ +export type SubscribeFunction = ( + request: RequestParameters, + variables: Variables, + cacheConfig: CacheConfig, + observer?: LegacyObserver, +) => RelayObservable | Disposable; + +export type Uploadable = File | Blob; +export interface UploadableMap { + [key: string]: Uploadable; +} diff --git a/types/relay-runtime/lib/network/RelayObservable.d.ts b/types/relay-runtime/lib/network/RelayObservable.d.ts new file mode 100644 index 0000000000..535f73accd --- /dev/null +++ b/types/relay-runtime/lib/network/RelayObservable.d.ts @@ -0,0 +1,190 @@ +/** + * A Subscription object is returned from .subscribe(), which can be + * unsubscribed or checked to see if the resulting subscription has closed. + */ +export interface Subscription { + unsubscribe(): void; + readonly closed: boolean; +} + +/** + * An Observer is an object of optional callback functions provided to + * .subscribe(). Each callback function is invoked when that event occurs. + */ +export interface Observer { + readonly start?: (subscription: Subscription) => void; + readonly next?: (value: T) => void; + readonly error?: (error: Error) => void; + readonly complete?: () => void; + readonly unsubscribe?: (subscription: Subscription) => void; +} + +/** + * A Sink is an object of methods provided by Observable during construction. + * The methods are to be called to trigger each event. It also contains a closed + * field to see if the resulting subscription has closed. + */ +export interface Sink { + next(value: T): void; + error(error: Error, isUncaughtThrownError?: boolean): void; + complete(): void; + readonly closed: boolean; +} + +/** + * A Source is the required argument when constructing a new Observable. Similar + * to a Promise constructor, this is a function which is invoked with a Sink, + * and may return either a cleanup function or a Subscription instance (for use + * when composing Observables). + */ +export type Source = (sink: Sink) => void | Subscription | (() => unknown); + +/** + * A Subscribable is an interface describing any object which can be subscribed. + * + * Note: A sink may be passed directly to .subscribe() as its observer, + * allowing for easily composing Subscribables. + */ +export interface Subscribable { + subscribe(observer: Observer | Sink): Subscription; +} + +export type ObservableFromValue = Subscribable | Promise | T; + +/** + * Limited implementation of ESObservable, providing the limited set of behavior + * Relay networking requires. + * + * Observables retain the benefit of callbacks which can be called + * synchronously, avoiding any UI jitter, while providing a compositional API, + * which simplifies logic and prevents mishandling of errors compared to + * the direct use of callback functions. + * + * ESObservable: https://github.com/tc39/proposal-observable + */ +export class RelayObservable implements Subscribable { + // Use RelayObservable.create(source); + private constructor(source: never); + + static create(source: Source): RelayObservable; + + /** + * When an emitted error event is not handled by an Observer, it is reported + * to the host environment (what the ESObservable spec refers to as + * "HostReportErrors()"). + * + * The default implementation in development rethrows thrown errors, and + * logs emitted error events to the console, while in production does nothing + * (swallowing unhandled errors). + * + * Called during application initialization, this method allows + * application-specific handling of unhandled errors. Allowing, for example, + * integration with error logging or developer tools. + * + * A second parameter `isUncaughtThrownError` is true when the unhandled error + * was thrown within an Observer handler, and false when the unhandled error + * was an unhandled emitted event. + * + * - Uncaught thrown errors typically represent avoidable errors thrown from + * application code, which should be handled with a try/catch block, and + * usually have useful stack traces. + * + * - Unhandled emitted event errors typically represent unavoidable events in + * application flow such as network failure, and may not have useful + * stack traces. + */ + static onUnhandledError(callback: (error: Error, isUncaughtThrownError: boolean) => void): void; + + /** + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ + static from(obj: ObservableFromValue): RelayObservable; + + /** + * Similar to promise.catch(), observable.catch() handles error events, and + * provides an alternative observable to use in it's place. + * + * If the catch handler throws a new error, it will appear as an error event + * on the resulting Observable. + */ + catch(fn: (error: Error) => RelayObservable): RelayObservable; + + /** + * Returns a new Observable which first yields values from this Observable, + * then yields values from the next Observable. This is useful for chaining + * together Observables of finite length. + */ + concat(next: RelayObservable): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ + do(observer: Observer): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ + finally(fn: () => unknown): RelayObservable; + + /** + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ + ifEmpty(alternate: RelayObservable): RelayObservable; + + /** + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + * + * Note: A sink may be passed directly to .subscribe() as its observer, + * allowing for easily composing Observables. + */ + subscribe(observer: Observer | Sink): Subscription; + + /** + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ + map(fn: (value: T) => U): RelayObservable; + + /** + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * merged Observable. + */ + mergeMap(fn: (value: T) => ObservableFromValue): RelayObservable; + + /** + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ + poll(pollInterval: number): RelayObservable; + + /** + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ + toPromise(): Promise; +} diff --git a/types/relay-runtime/lib/network/RelayQueryResponseCache.d.ts b/types/relay-runtime/lib/network/RelayQueryResponseCache.d.ts new file mode 100644 index 0000000000..d8ab27b3cb --- /dev/null +++ b/types/relay-runtime/lib/network/RelayQueryResponseCache.d.ts @@ -0,0 +1,9 @@ +import { GraphQLResponse } from '../network/RelayNetworkTypes'; +import { Variables } from '../util/RelayRuntimeTypes'; + +export default class RelayQueryResponseCache { + constructor(config: { size: number; ttl: number }); + clear(): void; + get(queryID: string, variables: Variables): GraphQLResponse | null; + set(queryID: string, variables: Variables, payload: GraphQLResponse): void; +} diff --git a/types/relay-runtime/lib/network/createRelayNetworkLogger.d.ts b/types/relay-runtime/lib/network/createRelayNetworkLogger.d.ts index 817a29e6b6..91e2d8b3ef 100644 --- a/types/relay-runtime/lib/network/createRelayNetworkLogger.d.ts +++ b/types/relay-runtime/lib/network/createRelayNetworkLogger.d.ts @@ -1,6 +1,7 @@ import { RelayNetworkLoggerTransaction } from './RelayNetworkLoggerTransaction'; import { RequestParameters } from '../util/RelayConcreteNode'; -import { Variables, FetchFunction, SubscribeFunction } from '../../index'; +import { Variables } from '../util/RelayRuntimeTypes'; +import { FetchFunction, SubscribeFunction } from './RelayNetworkTypes'; export type GraphiQLPrinter = (request: RequestParameters, variables: Variables) => string; export interface NetworkLogger { diff --git a/types/relay-runtime/lib/query/RelayModernGraphQLTag.d.ts b/types/relay-runtime/lib/query/RelayModernGraphQLTag.d.ts new file mode 100644 index 0000000000..5805b7ca0c --- /dev/null +++ b/types/relay-runtime/lib/query/RelayModernGraphQLTag.d.ts @@ -0,0 +1,34 @@ +import { + ReaderFragment, + ReaderPaginationFragment, + ReaderRefetchableFragment, + ReaderInlineDataFragment, +} from '../util/ReaderNode'; +import { ConcreteRequest } from '../util/RelayConcreteNode'; + +// The type of a graphql`...` tagged template expression. +export type GraphQLTaggedNode = ReaderFragment | ConcreteRequest | (() => ReaderFragment | ConcreteRequest); + +/** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ +export function graphql(strings: unknown): GraphQLTaggedNode; + +export function getNode(taggedNode: unknown): unknown; + +export function isFragment(node: GraphQLTaggedNode): boolean; + +export function isRequest(node: GraphQLTaggedNode): boolean; + +export function isInlineDataFragment(node: GraphQLTaggedNode): boolean; + +export function getFragment(taggedNode: GraphQLTaggedNode): ReaderFragment; + +export function getPaginationFragment(taggedNode: GraphQLTaggedNode): ReaderPaginationFragment | null; + +export function getRefetchableFragment(taggedNode: GraphQLTaggedNode): ReaderRefetchableFragment | null; + +export function getRequest(taggedNode: GraphQLTaggedNode): ConcreteRequest; + +export function getInlineDataFragment(taggedNode: GraphQLTaggedNode): ReaderInlineDataFragment; diff --git a/types/relay-runtime/lib/query/fetchQuery.d.ts b/types/relay-runtime/lib/query/fetchQuery.d.ts new file mode 100644 index 0000000000..a8e6fc7340 --- /dev/null +++ b/types/relay-runtime/lib/query/fetchQuery.d.ts @@ -0,0 +1,10 @@ +import { OperationType, CacheConfig } from '../util/RelayRuntimeTypes'; +import { Environment } from '../store/RelayStoreTypes'; +import { GraphQLTaggedNode } from './RelayModernGraphQLTag'; + +export function fetchQuery( + environment: Environment, + taggedNode: GraphQLTaggedNode, + variables: T['variables'], + cacheConfig?: CacheConfig | null, +): Promise; diff --git a/types/relay-runtime/lib/store/RelayConnection.d.ts b/types/relay-runtime/lib/store/RelayConnection.d.ts new file mode 100644 index 0000000000..81539672ec --- /dev/null +++ b/types/relay-runtime/lib/store/RelayConnection.d.ts @@ -0,0 +1,82 @@ +import { Variables } from '../util/RelayRuntimeTypes'; +import { RequestDescriptor, TypedSnapshot, RecordMap } from './RelayStoreTypes'; +import { ReaderLinkedField } from '../util/ReaderNode'; + +export type ConnectionID = string; + +export interface ConnectionRecord { + __id: ConnectionID; + __typename: string; + events: ConnectionInternalEvent[]; +} + +export interface ConnectionMap { + [key: string]: ConnectionRecord; +} + +export type GetConnectionEvents = (connectionID: ConnectionID) => ReadonlyArray; + +export type ConnectionInternalEvent = + | { + kind: string; + args: Variables; + connectionID: ConnectionID; + edgeIDs: ReadonlyArray; + pageInfo: PageInfo; + request: RequestDescriptor; + } + | { + kind: string; + args: Variables; + connectionID: ConnectionID; + edgeID: string; + request: RequestDescriptor; + }; + +export type ConnectionEvent = + | { + kind: 'fetch'; + args: Variables; + edges: ReadonlyArray; + pageInfo: PageInfo; + } + | { kind: 'update'; edgeData: { [key: string]: TEdge } } + | { kind: 'insert'; args: Variables; edge: TEdge }; + +export interface ConnectionResolver { + initialize(): TState; + reduce(state: TState, event: ConnectionEvent): TState; +} + +export interface ConnectionReferenceObject { + __connection: ConnectionReference; +} + +export interface ConnectionReference { + variables: Variables; + edgesField: ReaderLinkedField; + id: ConnectionID; + label: string; +} + +export interface ConnectionSnapshot { + edgeSnapshots: { [key: string]: TypedSnapshot }; + id: ConnectionID; + reference: ConnectionReference; + seenRecords: RecordMap; + state: TState; +} + +export interface PageInfo { + endCursor: string; + hasNextPage: boolean; + hasPrevPage: boolean; + startCursor: string; +} + +export const CONNECTION_KEY: string; +export const CONNECTION_TYPENAME: string; + +export function createConnectionID(parentID: string, label: string): ConnectionID; + +export function createConnectionRecord(connectionID: ConnectionID): ConnectionRecord; diff --git a/types/relay-runtime/lib/store/RelayModernEnvironment.d.ts b/types/relay-runtime/lib/store/RelayModernEnvironment.d.ts new file mode 100644 index 0000000000..4823944eb5 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernEnvironment.d.ts @@ -0,0 +1,82 @@ +import { HandlerProvider } from '../handlers/RelayDefaultHandlerProvider'; +import { + LogFunction, + OperationLoader, + Store, + MissingFieldHandler, + OperationTracker, + LoggerProvider, + Logger, + OptimisticUpdate, + OperationDescriptor, + SelectorStoreUpdater, + NormalizationSelector, + StoreUpdater, + SingularReaderSelector, + Snapshot, + OptimisticResponseConfig, + Environment, +} from './RelayStoreTypes'; +import { Network, PayloadData, GraphQLResponse, UploadableMap } from '../network/RelayNetworkTypes'; +import { TaskScheduler } from './RelayModernQueryExecutor'; +import { RelayOperationTracker } from './RelayOperationTracker'; +import { LoggerTransactionConfig } from '../network/RelayNetworkLoggerTransaction'; +import { Disposable, CacheConfig } from '../util/RelayRuntimeTypes'; +import { RelayObservable } from '../network/RelayObservable'; + +export interface EnvironmentConfig { + configName?: string; + handlerProvider?: HandlerProvider; + log?: LogFunction; + operationLoader?: OperationLoader; + network: Network; + scheduler?: TaskScheduler; + store: Store; + missingFieldHandlers?: ReadonlyArray; + operationTracker?: OperationTracker; + loggerProvider?: LoggerProvider; +} + +export class RelayModernEnvironment implements Environment { + readonly configName: string | null | undefined; + constructor(config: EnvironmentConfig); + getStore(): Store; + getNetwork(): Network; + getOperationTracker(): RelayOperationTracker; + getLogger(config: LoggerTransactionConfig): Logger; + applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable; + revertUpdate(update: OptimisticUpdate): void; + replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; + applyMutation(optimisticConfig: OptimisticResponseConfig): Disposable; + check(readSelector: NormalizationSelector): boolean; + commitPayload(operationDescriptor: OperationDescriptor, payload: PayloadData): void; + commitUpdate(updater: StoreUpdater): void; + lookup(readSelector: SingularReaderSelector): Snapshot; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; + retain(selector: NormalizationSelector): Disposable; + execute(data: { + operation: OperationDescriptor; + cacheConfig?: CacheConfig | null; + updater?: SelectorStoreUpdater | null; + }): RelayObservable; + executeMutation({ + operation, + optimisticResponse, + optimisticUpdater, + updater, + uploadables, + }: { + operation: OperationDescriptor; + optimisticUpdater?: SelectorStoreUpdater | null; + optimisticResponse?: object | null; + updater?: SelectorStoreUpdater | null; + uploadables?: UploadableMap | null; + }): RelayObservable; + executeWithSource({ + operation, + source, + }: { + operation: OperationDescriptor; + source: RelayObservable; + }): RelayObservable; +} diff --git a/types/relay-runtime/lib/store/RelayModernOperationDescriptor.d.ts b/types/relay-runtime/lib/store/RelayModernOperationDescriptor.d.ts new file mode 100644 index 0000000000..6eeed1c84a --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernOperationDescriptor.d.ts @@ -0,0 +1,12 @@ +import { ConcreteRequest } from '../util/RelayConcreteNode'; +import { Variables } from '../util/RelayRuntimeTypes'; +import { OperationDescriptor, RequestDescriptor } from './RelayStoreTypes'; +/** + * Creates an instance of the `OperationDescriptor` type defined in + * `RelayStoreTypes` given an operation and some variables. The input variables + * are filtered to exclude variables that do not match defined arguments on the + * operation, and default values are populated for null values. + */ +export function createOperationDescriptor(request: ConcreteRequest, variables: Variables): OperationDescriptor; + +export function createRequestDescriptor(request: ConcreteRequest, variables: Variables): RequestDescriptor; diff --git a/types/relay-runtime/lib/store/RelayModernQueryExecutor.d.ts b/types/relay-runtime/lib/store/RelayModernQueryExecutor.d.ts new file mode 100644 index 0000000000..45a0e34829 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernQueryExecutor.d.ts @@ -0,0 +1,29 @@ +import { + OperationDescriptor, + OperationLoader, + OperationTracker, + OptimisticResponseConfig, + PublishQueue, + SelectorStoreUpdater, +} from './RelayStoreTypes'; +import { GraphQLResponse } from '../network/RelayNetworkTypes'; +import { Sink, RelayObservable } from '../network/RelayObservable'; +import { GetDataID } from './RelayResponseNormalizer'; + +export interface ExecuteConfig { + getDataID: GetDataID; + operation: OperationDescriptor; + operationLoader: OperationLoader; + operationTracker?: OperationTracker; + optimisticConfig: OptimisticResponseConfig; + publishQueue: PublishQueue; + scheduler?: TaskScheduler; + sink: Sink; + source: RelayObservable; + updater?: SelectorStoreUpdater; +} + +export interface TaskScheduler { + cancel: (id: string) => void; + schedule: (fn: () => void) => string; +} diff --git a/types/relay-runtime/lib/store/RelayModernRecord.d.ts b/types/relay-runtime/lib/store/RelayModernRecord.d.ts new file mode 100644 index 0000000000..478102319d --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernRecord.d.ts @@ -0,0 +1,85 @@ +import { Record } from './RelayStoreTypes'; +import { DataID } from '../util/RelayRuntimeTypes'; + +export class RelayModernRecord { + /** + * Clone a record. + */ + clone(record: Record): Record; + + /** + * Copies all fields from `source` to `sink`, excluding `__id` and `__typename`. + * + * NOTE: This function does not treat `id` specially. To preserve the id, + * manually reset it after calling this function. Also note that values are + * copied by reference and not value; callers should ensure that values are + * copied on write. + */ + copyFields(source: Record, sink: Record): void; + + /** + * Create a new record. + */ + create(dataID: DataID, typeName: string): Record; + + /** + * Get the record's `id` if available or the client-generated identifier. + */ + getDataID(record: Record): DataID; + + /** + * Get the concrete type of the record. + */ + getType(record: Record): string; + + /** + * Get a scalar (non-link) field value. + */ + getValue(record: Record, storageKey: string): unknown; + + /** + * Get the value of a field as a reference to another record. Throws if the + * field has a different type. + */ + getLinkedRecordID(record: Record, storageKey: string): DataID | null; + + /** + * Get the value of a field as a list of references to other records. Throws if + * the field has a different type. + */ + getLinkedRecordIDs(record: Record, storageKey: string): DataID[] | null; + + /** + * Compares the fields of a previous and new record, returning either the + * previous record if all fields are equal or a new record (with merged fields) + * if any fields have changed. + */ + update(prevRecord: Record, nextRecord: Record): Record; + + /** + * Returns a new record with the contents of the given records. Fields in the + * second record will overwrite identical fields in the first record. + */ + merge(record1: Record, record2: Record): Record; + + /** + * Prevent modifications to the record. Attempts to call `set*` functions on a + * frozen record will fatal at runtime. + */ + freeze(record: Record): void; + + /** + * Set the value of a storageKey to a scalar. + */ + setValue(record: Record, storageKey: string, value: any): void; + + /** + * Set the value of a field to a reference to another record. + */ + setLinkedRecordID(record: Record, storageKey: string, linkedID: DataID): void; + + /** + * Set the value of a field to a list of references other records. + */ + setLinkedRecordIDs(record: Record, storageKey: string, linkedIDs: DataID[] | null): void; +} diff --git a/types/relay-runtime/lib/store/RelayModernSelector.d.ts b/types/relay-runtime/lib/store/RelayModernSelector.d.ts new file mode 100644 index 0000000000..8923c7392a --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernSelector.d.ts @@ -0,0 +1,115 @@ +import { ReaderFragment } from '../util/ReaderNode'; +import { + SingularReaderSelector, + PluralReaderSelector, + ReaderSelector, + RequestDescriptor, + NormalizationSelector, +} from './RelayStoreTypes'; +import { DataID, Variables } from '../util/RelayRuntimeTypes'; +import { NormalizationSelectableNode } from '../util/NormalizationNode'; + +/** + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSingularSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ +export function getSingularSelector(fragment: ReaderFragment, item: unknown): SingularReaderSelector; + +/** + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSingularSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ +export function getPluralSelector(fragment: ReaderFragment, items: unknown[]): PluralReaderSelector; + +export function getSelector(fragment: ReaderFragment, item: unknown | unknown[]): ReaderSelector; + +/** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function is ReactRelayFragmentContainer, which + * uses this function to convert (props, fragments) into selectors so that it + * can read the results to pass to the inner component. + */ +export function getSelectorsFromObject( + fragments: { [key: string]: ReaderFragment }, + object: { [key: string]: any }, +): { [key: string]: ReaderSelector }; + +/** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ +export function getDataIDsFromObject( + fragments: { [key: string]: ReaderFragment }, + object: { [key: string]: any }, +): { [key: string]: DataID | DataID[] }; + +export function getDataIDsFromFragment(fragment: ReaderFragment, item: unknown | unknown[]): DataID | DataID[]; + +/** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ +export function getVariablesFromObject( + fragments: { [key: string]: ReaderFragment }, + object: { [key: string]: any }, +): Variables; + +export function getVariablesFromFragment(fragment: ReaderFragment, item: unknown | unknown[]): Variables; + +export function getVariablesFromSingularFragment(fragment: ReaderFragment, item: unknown): Variables; + +export function getVariablesFromPluralFragment(fragment: ReaderFragment, items: unknown[]): Variables; + +/** + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ +export function areEqualSelectors(thisSelector: SingularReaderSelector, thatSelector: SingularReaderSelector): boolean; + +export function createReaderSelector( + fragment: ReaderFragment, + dataID: DataID, + variables: Variables, + request: RequestDescriptor, +): SingularReaderSelector; + +export function createNormalizationSelector( + node: NormalizationSelectableNode, + dataID: DataID, + variables: Variables, +): NormalizationSelector; diff --git a/types/relay-runtime/lib/store/RelayModernStore.d.ts b/types/relay-runtime/lib/store/RelayModernStore.d.ts new file mode 100644 index 0000000000..2264a1fee7 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayModernStore.d.ts @@ -0,0 +1,46 @@ +import { + Store, + MutableRecordSource, + Scheduler, + OperationLoader, + RecordSource, + NormalizationSelector, + ReaderSelector, + Snapshot, + RequestDescriptor, +} from './RelayStoreTypes'; +import { Disposable } from '../util/RelayRuntimeTypes'; +import { + ConnectionReference, + ConnectionResolver, + ConnectionSnapshot, + ConnectionInternalEvent, + ConnectionID, +} from './RelayConnection'; + +export class RelayModernStore implements Store { + constructor(source: MutableRecordSource, gcScheduler?: Scheduler, operationLoader?: OperationLoader | null); + getSource(): RecordSource; + check(selector: NormalizationSelector): boolean; + retain(selector: NormalizationSelector): Disposable; + lookup(selector: ReaderSelector): Snapshot; + notify(): ReadonlyArray; + publish(source: RecordSource): void; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; + holdGC(): Disposable; + toJSON(): unknown; + lookupConnection_UNSTABLE( + connectionReference: ConnectionReference, + resolver: ConnectionResolver, + ): ConnectionSnapshot; + + subscribeConnection_UNSTABLE( + snapshot: ConnectionSnapshot, + resolver: ConnectionResolver, + callback: (state: TState) => void, + ): Disposable; + publishConnectionEvents_UNSTABLE(events: ConnectionInternalEvent[], final: boolean): void; + getConnectionEvents_UNSTABLE(connectionID: ConnectionID): ReadonlyArray; + snapshot(): void; + restore(): void; +} diff --git a/types/relay-runtime/lib/store/RelayOperationTracker.d.ts b/types/relay-runtime/lib/store/RelayOperationTracker.d.ts new file mode 100644 index 0000000000..8416990854 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayOperationTracker.d.ts @@ -0,0 +1,19 @@ +import { RequestDescriptor } from './RelayStoreTypes'; + +export class RelayOperationTracker { + /** + * Update the map of current processing operations with the set of + * affected owners and notify subscribers + */ + update(pendingOperation: RequestDescriptor, affectedOwners: Set): void; + + /** + * Once pending operation is completed we need to remove it + * from all tracking maps + */ + complete(pendingOperation: RequestDescriptor): void; + + _resolveOwnerResolvers(owner: RequestDescriptor): void; + + getPromiseForPendingOperationsAffectingOwner(owner: RequestDescriptor): Promise | null; +} diff --git a/types/relay-runtime/lib/store/RelayRecordSource.d.ts b/types/relay-runtime/lib/store/RelayRecordSource.d.ts new file mode 100644 index 0000000000..be816e39d2 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayRecordSource.d.ts @@ -0,0 +1,21 @@ +import { MutableRecordSource, RecordMap, Record } from './RelayStoreTypes'; +import { DataID } from '../util/RelayRuntimeTypes'; +import { RecordState } from './RelayRecordState'; + +export class RelayRecordSource { + constructor(records?: RecordMap); + + static create(records?: RecordMap): MutableRecordSource; + + clear(): void; + delete(dataID: DataID): void; + get(dataID: DataID): Record; + getRecordIDs(): string[]; + getStatus(dataID: DataID): RecordState; + has(dataID: DataID): boolean; + load(dataID: DataID, callback: (error: Error | null | undefined, record: Record | null | undefined) => void): void; + remove(dataID: DataID): void; + set(dataID: DataID, record: Record): void; + size(): number; + toJSON(): Record; +} diff --git a/types/relay-runtime/lib/store/RelayRecordState.d.ts b/types/relay-runtime/lib/store/RelayRecordState.d.ts new file mode 100644 index 0000000000..d9757ea384 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayRecordState.d.ts @@ -0,0 +1 @@ +export type RecordState = 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; diff --git a/types/relay-runtime/lib/store/RelayResponseNormalizer.d.ts b/types/relay-runtime/lib/store/RelayResponseNormalizer.d.ts new file mode 100644 index 0000000000..4370810423 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayResponseNormalizer.d.ts @@ -0,0 +1,21 @@ +import { RequestDescriptor, MutableRecordSource, NormalizationSelector, RelayResponsePayload } from './RelayStoreTypes'; +import { PayloadData } from '../network/RelayNetworkTypes'; + +export type GetDataID = (fieldValue: { [key: string]: any }, typeName: string) => any; + +export interface NormalizationOptions { + getDataID: GetDataID; + path?: ReadonlyArray; + request: RequestDescriptor; +} + +/** + * Normalizes the results of a query and standard GraphQL response, writing the + * normalized records/fields into the given MutableRecordSource. + */ +export function normalize( + recordSource: MutableRecordSource, + selector: NormalizationSelector, + response: PayloadData, + options: NormalizationOptions, +): RelayResponsePayload; diff --git a/types/relay-runtime/lib/store/RelayStoreTypes.d.ts b/types/relay-runtime/lib/store/RelayStoreTypes.d.ts new file mode 100644 index 0000000000..b09a7bd8fc --- /dev/null +++ b/types/relay-runtime/lib/store/RelayStoreTypes.d.ts @@ -0,0 +1,781 @@ +import { ReaderFragment } from '../util/ReaderNode'; +import { Variables, Disposable, DataID, CacheConfig } from '../util/RelayRuntimeTypes'; +import { ConcreteRequest, RequestParameters } from '../util/RelayConcreteNode'; +import { RequestIdentifier } from '../util/getRequestIdentifier'; +import { + NormalizationSelectableNode, + NormalizationSplitOperation, + NormalizationScalarField, + NormalizationLinkedField, +} from '../util/NormalizationNode'; +import { Environment, RecordState, GraphQLResponse, StoreUpdater, SelectorStoreUpdater } from '../..'; +import { + ConnectionReference, + ConnectionResolver, + ConnectionSnapshot, + ConnectionInternalEvent, + ConnectionID, +} from './RelayConnection'; +import { LoggerTransactionConfig } from '../network/RelayNetworkLoggerTransaction'; +import { PayloadData, Network, UploadableMap, PayloadError } from '../network/RelayNetworkTypes'; +import { RelayObservable } from '../network/RelayObservable'; +import { RelayOperationTracker } from './RelayOperationTracker'; + +export type FragmentReference = unknown; +export type OperationTracker = RelayOperationTracker; + +/* + * An individual cached graph object. + */ +export interface Record { + [key: string]: any; +} + +/** + * A collection of records keyed by id. + */ +export interface RecordMap { + // theoretically, this should be `[dataID: DataID]`, but `DataID` is a string. + [dataID: string]: Record; +} + +export interface FragmentMap { + [key: string]: ReaderFragment; +} + +/** + * The results of a selector given a store/RecordSource. + */ +export interface SelectorData { + [key: string]: any; +} + +export interface SingularReaderSelector { + kind: string; + dataID: string; + node: ReaderFragment; + owner: RequestDescriptor; + variables: Variables; +} + +export type ReaderSelector = SingularReaderSelector | PluralReaderSelector; + +export interface PluralReaderSelector { + kind: string; + selectors: ReadonlyArray; +} + +export interface RequestDescriptor { + identifier: RequestIdentifier; + node: ConcreteRequest; + variables: Variables; +} + +/** + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ +export interface NormalizationSelector { + dataID: string; + node: NormalizationSelectableNode; + variables: Variables; +} + +/** + * A representation of a selector and its results at a particular point in time. + */ +export interface TypedSnapshot { + data: TData; + isMissingData: boolean; + seenRecords: RecordMap; + selector: SingularReaderSelector; +} +export type Snapshot = TypedSnapshot; + +/** + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ +export interface OperationDescriptor { + fragment: SingularReaderSelector; + request: RequestDescriptor; + root: NormalizationSelector; +} + +/** + * Arbitrary data e.g. received by a container as props. + */ +export interface Props { + [key: string]: any; +} + +/** + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ +export interface RelayContext { + environment: Environment; + variables: Variables; +} + +/** + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ +export interface FragmentSpecResults { + [key: string]: any; +} + +/** + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ +export interface FragmentSpecResolver { + /** + * Stop watching for changes to the results of the fragments. + */ + dispose(): void; + + /** + * Get the current results. + */ + resolve(): FragmentSpecResults; + + /** + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. + */ + setProps(props: Props): void; + + /** + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ + setVariables(variables: Variables, node: ConcreteRequest): void; + + /** + * Subscribe to resolver updates. + * Overrides existing callback (if one has been specified). + */ + setCallback(callback: () => void): void; +} + +/** + * A read-only interface for accessing cached graph data. + */ +export interface RecordSource { + get(dataID: string): Record; + getRecordIDs(): string[]; + getStatus(dataID: string): RecordState; + has(dataID: string): boolean; + size(): number; + toJSON(): { [key: string]: Record }; +} + +/** + * A read/write interface for accessing and updating graph data. + */ +export interface MutableRecordSource extends RecordSource { + clear(): void; + delete(dataID: string): void; + remove(dataID: string): void; + set(dataID: string, record: Record): void; +} + +/** + * An interface for keeping multiple views of data consistent across an + * application. + */ +export interface Store { + /** + * Get a read-only view of the store's internal RecordSource. + */ + getSource(): RecordSource; + + /** + * Determine if the selector can be resolved with data in the store (i.e. no + * fields are missing). + */ + check(selector: NormalizationSelector): boolean; + + /** + * Read the results of a selector from in-memory records in the store. + * Optionally takes an owner, corresponding to the operation that + * owns this selector (fragment). + */ + lookup(selector: SingularReaderSelector): Snapshot; + + /** + * Notify subscribers (see `subscribe`) of any data that was published + * (`publish()`) since the last time `notify` was called. + * + * Also this method should return an array of the affected fragment owners + */ + notify(): ReadonlyArray; + + /** + * Publish new information (e.g. from the network) to the store, updating its + * internal record source. Subscribers are not immediately notified - this + * occurs when `notify()` is called. + */ + publish(source: RecordSource): void; + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + */ + retain(selector: NormalizationSelector): Disposable; + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when `notify()` is called *and* records have been published that affect the + * selector results relative to the last `notify()`. + */ + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; + + /** + * The method should disable garbage collection until + * the returned reference is disposed. + */ + holdGC(): Disposable; + + lookupConnection_UNSTABLE( + connectionReference: ConnectionReference, + resolver: ConnectionResolver, + ): ConnectionSnapshot; + + subscribeConnection_UNSTABLE( + snapshot: ConnectionSnapshot, + resolver: ConnectionResolver, + callback: (state: TState) => void, + ): Disposable; + + /** + * Publish connection events, updating the store's list of events. As with + * publish(), subscribers are only notified after notify() is called. + */ + publishConnectionEvents_UNSTABLE(events: ConnectionInternalEvent[], final: boolean): void; + + /** + * Get a read-only view of the store's internal connection events for a given + * connection. + */ + getConnectionEvents_UNSTABLE(connectionID: ConnectionID): ReadonlyArray; + + /** + * Record a backup/snapshot of the current state of the store, including + * records and derived data such as fragment and connection subscriptions. + * This state can be restored with restore(). + */ + snapshot(): void; + + /** + * Reset the state of the store to the point that snapshot() was last called. + */ + restore(): void; +} + +/** + * A type that accepts a callback and schedules it to run at some future time. + * By convention, implementations should not execute the callback immediately. + */ +export type Scheduler = (callback: () => void) => void; + +/** + * An interface for imperatively getting/setting properties of a `Record`. This interface + * is designed to allow the appearance of direct Record manipulation while + * allowing different implementations that may e.g. create a changeset of + * the modifications. + */ +export interface RecordProxy { + copyFieldsFrom(source: RecordProxy): void; + getDataID(): DataID; + getLinkedRecord(name: string, args?: Variables): RecordProxy; + getLinkedRecords(name: string, args?: Variables): RecordProxy[]; + getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables): RecordProxy; + getType(): string; + getValue(name: string, args?: Variables): any; + setLinkedRecord(record: RecordProxy, name: string, args?: Variables): RecordProxy; + setLinkedRecords(records: RecordProxy[], name: string, args?: Variables): RecordProxy; + setValue(value: any, name: string, args?: Variables): RecordProxy; +} + +export interface ReadOnlyRecordProxy { + getDataID(): DataID; + getLinkedRecord(name: string, args?: Variables): RecordProxy; + getLinkedRecords(name: string, args?: Variables): RecordProxy[]; + getType(): string; + getValue(name: string, args?: Variables): any; +} + +/** + * An interface for imperatively getting/setting properties of a `RecordSource`. This interface + * is designed to allow the appearance of direct RecordSource manipulation while + * allowing different implementations that may e.g. create a changeset of + * the modifications. + */ +export interface RecordSourceProxy { + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): RecordProxy; + getRoot(): RecordProxy; +} + +export interface ReadOnlyRecordSourceProxy { + get(dataID: DataID): ReadOnlyRecordProxy; + getRoot(): ReadOnlyRecordProxy; +} + +/** + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ +export interface RecordSourceSelectorProxy extends RecordSourceProxy { + getRootField(fieldName: string): RecordProxy; + getPluralRootField(fieldName: string): RecordProxy[]; + insertConnectionEdge_UNSTABLE(connectionID: ConnectionID, args: Variables, edge: RecordProxy): void; +} + +export interface Logger { + log(message: string, ...values: any[]): void; + flushLogs(): void; +} + +export interface LoggerProvider { + getLogger(config: LoggerTransactionConfig): Logger; +} + +export type LogEvent = + | { + name: string; + transactionID: number; + info: any; + } + | { + name: string; + transactionID: number; + params: RequestParameters; + variables: Variables; + } + | { + name: string; + transactionID: number; + response: GraphQLResponse; + } + | { + name: string; + transactionID: number; + error: Error; + } + | { + name: string; + transactionID: number; + } + | { + name: string; + transactionID: number; + }; +export type LogFunction = (logEvent: LogEvent) => void; +export type LogRequestInfoFunction = (arg: any) => void; + +/** + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ +export interface Environment { + /** + * Determine if the selector can be resolved with data in the store (i.e. no + * fields are missing). + * + * Note that this operation effectively "executes" the selector against the + * cache and therefore takes time proportional to the size/complexity of the + * selector. + */ + check(selector: NormalizationSelector): boolean; + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + */ + retain(selector: NormalizationSelector): Disposable; + + /** + * Apply an optimistic update to the environment. The mutation can be reverted + * by calling `dispose()` on the returned value. + */ + applyUpdate(optimisticUpdate: OptimisticUpdateFunction): Disposable; + + /** + * Apply an optimistic mutation response and/or updater. The mutation can be + * reverted by calling `dispose()` on the returned value. + */ + applyMutation(optimisticConfig: OptimisticResponseConfig): Disposable; + + /** + * Commit an updater to the environment. This mutation cannot be reverted and + * should therefore not be used for optimistic updates. This is mainly + * intended for updating fields from client schema extensions. + */ + commitUpdate(updater: StoreUpdater): void; + + /** + * Commit a payload to the environment using the given operation selector. + */ + commitPayload(operationDescriptor: OperationDescriptor, payload: PayloadData): void; + + /** + * Get the environment's internal Network. + */ + getNetwork(): Network; + + /** + * Get the environment's internal Store. + */ + getStore(): Store; + + /** + * Get an instance of a logger + */ + getLogger(config: LoggerTransactionConfig): Logger; + + /** + * Returns the environment specific OperationTracker. + */ + getOperationTracker(): RelayOperationTracker; + + /** + * Read the results of a selector from in-memory records in the store. + * Optionally takes an owner, corresponding to the operation that + * owns this selector (fragment). + */ + lookup(selector: SingularReaderSelector): Snapshot; + + /** + * Send a query to the server with Observer semantics: one or more + * responses may be returned (via `next`) over time followed by either + * the request completing (`completed`) or an error (`error`). + * + * Networks/servers that support subscriptions may choose to hold the + * subscription open indefinitely such that `complete` is not called. + * + * Note: Observables are lazy, so calling this method will do nothing until + * the result is subscribed to: environment.execute({...}).subscribe({...}). + */ + execute(config: { + operation: OperationDescriptor; + cacheConfig?: CacheConfig; + updater?: SelectorStoreUpdater; + }): RelayObservable; + + /** + * Returns an Observable of GraphQLResponse resulting from executing the + * provided Mutation operation, the result of which is then normalized and + * committed to the publish queue along with an optional optimistic response + * or updater. + * + * Note: Observables are lazy, so calling this method will do nothing until + * the result is subscribed to: + * environment.executeMutation({...}).subscribe({...}). + */ + executeMutation({ + operation, + optimisticUpdater, + optimisticResponse, + updater, + uploadables, + }: { + operation: OperationDescriptor; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: object; + updater?: SelectorStoreUpdater; + uploadables?: UploadableMap; + }): RelayObservable; + + /** + * Returns an Observable of GraphQLResponse resulting from executing the + * provided Query or Subscription operation responses, the result of which is + * then normalized and comitted to the publish queue. + * + * Note: Observables are lazy, so calling this method will do nothing until + * the result is subscribed to: + * environment.executeWithSource({...}).subscribe({...}). + */ + executeWithSource({ + operation, + source, + }: { + operation: OperationDescriptor; + source: RelayObservable; + }): RelayObservable; +} + +/** + * The results of reading data for a fragment. This is similar to a `Selector`, + * but references the (fragment) node by name rather than by value. + */ +export interface FragmentPointer { + __id: DataID; + __fragments: { [fragmentName: string]: Variables }; + __fragmentOwner: RequestDescriptor; +} + +/** + * The partial shape of an object with a '...Fragment @module(name: "...")' + * selection + */ +export interface ModuleImportPointer { + __fragmentPropName: string; + __module_component: any; + fragmentRefs: any; +} + +/** + * A callback for resolving a Selector from a source. + */ +export type AsyncLoadCallback = (loadingState: LoadingState) => void; +export interface LoadingState { + status: 'aborted' | 'complete' | 'error' | 'missing'; + error?: Error; +} + +/** + * A map of records affected by an update operation. + */ +export interface UpdatedRecords { + [dataID: string]: boolean; +} + +/** + * A function that updates a store (via a proxy) given the results of a "handle" + * field payload. + */ +export class Handler { + update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; +} + +/** + * A payload that is used to initialize or update a "handle" field with + * information from the server. + */ +export interface HandleFieldPayload { + // The arguments that were fetched. + args: Variables; + // The __id of the record containing the source/handle field. + dataID: DataID; + // The (storage) key at which the original server data was written. + fieldKey: string; + // The name of the handle. + handle: string; + // The (storage) key at which the handle's data should be written by the + // handler. + handleKey: string; +} + +/** + * A payload that represents data necessary to process the results of an object + * with a `@module` fragment spread: + * - data: The GraphQL response value for the @match field. + * - dataID: The ID of the store object linked to by the @match field. + * - operationReference: A reference to a generated module containing the + * SplitOperation with which to normalize the field's `data`. + * - variables: Query variables. + * - typeName: the type that matched. + * + * The dataID, variables, and fragmentName can be used to create a Selector + * which can in turn be used to normalize and publish the data. The dataID and + * typeName can also be used to construct a root record for normalization. + */ +export interface ModuleImportPayload { + data: PayloadData; + dataID: DataID; + operationReference: any; + path: ReadonlyArray; + typeName: string; + variables: Variables; +} + +/** + * Data emitted after processing a Defer or Stream node during normalization + * that describes how to process the corresponding response chunk when it + * arrives. + */ +export interface DeferPlaceholder { + kind: 'defer'; + data: PayloadData; + label: string; + path: ReadonlyArray; + selector: NormalizationSelector; + typeName: string; +} +export interface StreamPlaceholder { + kind: 'stream'; + label: string; + path: ReadonlyArray; + parentID: DataID; + node: NormalizationSelectableNode; + variables: Variables; +} +export type IncrementalDataPlaceholder = DeferPlaceholder | StreamPlaceholder; + +/** + * A user-supplied object to load a generated operation (SplitOperation) AST + * by a module reference. The exact format of a module reference is left to + * the application, but it must be a plain JavaScript value (string, number, + * or object/array of same). + */ +export interface OperationLoader { + /** + * Synchronously load an operation, returning either the node or null if it + * cannot be resolved synchronously. + */ + get(reference: any): NormalizationSplitOperation; + + /** + * Asynchronously load an operation. + */ + load(reference: any): Promise; +} + +/** + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ +export type StoreUpdater = (store: RecordSourceProxy) => void; + +/** + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ +export type SelectorStoreUpdater = (store: RecordSourceSelectorProxy, data: T) => void; + +/** + * A set of configs that can be used to apply an optimistic update into the + * store. + */ +export type OptimisticUpdate = OptimisticUpdateFunction | OptimisticUpdateRelayPayload; + +export interface OptimisticUpdateFunction { + storeUpdater: StoreUpdater; +} + +export interface OptimisticUpdateRelayPayload { + operation: OperationDescriptor; + payload: RelayResponsePayload; + updater: SelectorStoreUpdater; +} + +export interface OptimisticResponseConfig { + operation: OperationDescriptor; + response: PayloadData; + updater: SelectorStoreUpdater; +} + +/** + * A set of handlers that can be used to provide substitute data for missing + * fields when reading a selector from a source. + */ +export type MissingFieldHandler = + | { + kind: string; + handle: ( + field: NormalizationScalarField, + record: Record, + args: Variables, + store: ReadOnlyRecordSourceProxy, + ) => any; + } + | { + kind: string; + handle: ( + field: NormalizationLinkedField, + record: Record, + args: Variables, + store: ReadOnlyRecordSourceProxy, + ) => DataID; + } + | { + kind: string; + handle: ( + field: NormalizationLinkedField, + record: Record, + args: Variables, + store: ReadOnlyRecordSourceProxy, + ) => DataID[]; + }; + +/** + * The results of normalizing a query. + */ +export interface RelayResponsePayload { + connectionEvents: ConnectionInternalEvent[]; + errors: PayloadError[]; + fieldPayloads: HandleFieldPayload[]; + incrementalPlaceholders: IncrementalDataPlaceholder[]; + moduleImportPayloads: ModuleImportPayload[]; + source: MutableRecordSource; +} + +/** + * Public interface for Publish Queue + */ +export interface PublishQueue { + /** + * Schedule applying an optimistic updates on the next `run()`. + */ + applyUpdate(updater: OptimisticUpdate): void; + + /** + * Schedule reverting an optimistic updates on the next `run()`. + */ + revertUpdate(updater: OptimisticUpdate): void; + + /** + * Schedule a revert of all optimistic updates on the next `run()`. + */ + revertAll(): void; + + /** + * Schedule applying a payload to the store on the next `run()`. + */ + commitPayload(operation: OperationDescriptor, payload: RelayResponsePayload, updater?: SelectorStoreUpdater): void; + + /** + * Schedule an updater to mutate the store on the next `run()` typically to + * update client schema fields. + */ + commitUpdate(updater: StoreUpdater): void; + + /** + * Schedule a publish to the store from the provided source on the next + * `run()`. As an example, to update the store with substituted fields that + * are missing in the store. + */ + commitSource(source: RecordSource): void; + + /** + * Execute all queued up operations from the other public methods. + */ + run(): ReadonlyArray; +} diff --git a/types/relay-runtime/lib/store/RelayStoreUtils.d.ts b/types/relay-runtime/lib/store/RelayStoreUtils.d.ts new file mode 100644 index 0000000000..9fe57d20c6 --- /dev/null +++ b/types/relay-runtime/lib/store/RelayStoreUtils.d.ts @@ -0,0 +1,79 @@ +import { NormalizationArgument, NormalizationHandle, NormalizationField } from '../util/NormalizationNode'; +import { ReaderArgument, ReaderField } from '../util/ReaderNode'; +import { Variables } from '../util/RelayRuntimeTypes'; + +export interface Arguments { + [key: string]: any; +} + +/** + * Returns the values of field/fragment arguments as an object keyed by argument + * names. Guaranteed to return a result with stable ordered nested values. + */ +export function getArgumentValues( + args: ReadonlyArray, + variables: Variables, +): Arguments; + +/** + * Given a handle field and variable values, returns a key that can be used to + * uniquely identify the combination of the handle name and argument values. + * + * Note: the word "storage" here refers to the fact this key is primarily used + * when writing the results of a key in a normalized graph or "store". This + * name was used in previous implementations of Relay internals and is also + * used here for consistency. + */ +export function getHandleStorageKey(handleField: NormalizationHandle, variables: Variables): string; + +/** + * Given a field and variable values, returns a key that can be used to + * uniquely identify the combination of the field name and argument values. + * + * Note: the word "storage" here refers to the fact this key is primarily used + * when writing the results of a key in a normalized graph or "store". This + * name was used in previous implementations of Relay internals and is also + * used here for consistency. + */ +export function getStorageKey( + field: NormalizationField | NormalizationHandle | ReaderField, + variables: Variables, +): string; + +/** + * Given a `name` (eg. "foo") and an object representing argument values + * (eg. `{orberBy: "name", first: 10}`) returns a unique storage key + * (ie. `foo{"first":10,"orderBy":"name"}`). + * + * This differs from getStorageKey which requires a ConcreteNode where arguments + * are assumed to already be sorted into a stable order. + */ +export function getStableStorageKey(name: string, args: Arguments): string; + +/** + * Given a name and argument values, format a storage key. + * + * Arguments and the values within them are expected to be ordered in a stable + * alphabetical ordering. + */ +export function formatStorageKey(name: string, argValues: Arguments): string; + +/** + * Given Variables and a variable name, return a variable value with + * all values in a stable order. + */ +export function getStableVariableValue(name: string, variables: Variables): unknown; + +export function getModuleComponentKey(documentName: string): string; +export function getModuleOperationKey(documentName: string): string; + +export const FRAGMENTS_KEY: string; +export const FRAGMENT_OWNER_KEY: string; +export const FRAGMENT_PROP_NAME_KEY: string; +export const MODULE_COMPONENT_KEY: string; // alias returned by Reader +export const ID_KEY: string; +export const REF_KEY: string; +export const REFS_KEY: string; +export const ROOT_ID: string; +export const ROOT_TYPE: string; +export const TYPENAME_KEY: string; diff --git a/types/relay-runtime/lib/store/createFragmentSpecResolver.d.ts b/types/relay-runtime/lib/store/createFragmentSpecResolver.d.ts new file mode 100644 index 0000000000..c6f906f37c --- /dev/null +++ b/types/relay-runtime/lib/store/createFragmentSpecResolver.d.ts @@ -0,0 +1,9 @@ +import { RelayContext, FragmentMap, Props, FragmentSpecResolver } from './RelayStoreTypes'; + +export function createFragmentSpecResolver( + context: RelayContext, + containerName: string, + fragments: FragmentMap, + props: Props, + callback?: () => void, +): FragmentSpecResolver; diff --git a/types/relay-runtime/lib/store/isRelayModernEnvironment.d.ts b/types/relay-runtime/lib/store/isRelayModernEnvironment.d.ts new file mode 100644 index 0000000000..c8331536ed --- /dev/null +++ b/types/relay-runtime/lib/store/isRelayModernEnvironment.d.ts @@ -0,0 +1 @@ +export function isRelayModernEnvironment(environment: any): boolean; diff --git a/types/relay-runtime/lib/subscription/requestSubscription.d.ts b/types/relay-runtime/lib/subscription/requestSubscription.d.ts new file mode 100644 index 0000000000..d6515f2b9f --- /dev/null +++ b/types/relay-runtime/lib/subscription/requestSubscription.d.ts @@ -0,0 +1,20 @@ +import { DeclarativeMutationConfig } from '../mutations/RelayDeclarativeMutationConfig'; +import { GraphQLTaggedNode } from '../query/RelayModernGraphQLTag'; +import { Variables, Disposable } from '../util/RelayRuntimeTypes'; +import { SelectorStoreUpdater, Environment } from '../store/RelayStoreTypes'; + +export interface GraphQLSubscriptionConfig { + configs?: ReadonlyArray; + subscription: GraphQLTaggedNode; + variables: Variables; + onCompleted?: () => void; + onError?: (error: Error) => void; + onNext?: (response: TSubscriptionPayload | null | undefined) => void; + updater?: SelectorStoreUpdater; +} + +export function requestSubscription( + environment: Environment, + // tslint:disable-next-line no-unnecessary-generics + config: GraphQLSubscriptionConfig, +): Disposable; diff --git a/types/relay-runtime/lib/util/NormalizationNode.d.ts b/types/relay-runtime/lib/util/NormalizationNode.d.ts index f711ca1645..0cae708053 100644 --- a/types/relay-runtime/lib/util/NormalizationNode.d.ts +++ b/types/relay-runtime/lib/util/NormalizationNode.d.ts @@ -94,6 +94,29 @@ export interface NormalizationVariable { readonly variableName: string; } +export interface NormalizationConnection { + kind: string; + label: string; + name: string; + args: ReadonlyArray; + edges: NormalizationLinkedField; + pageInfo: NormalizationLinkedField; +} + +export interface NormalizationLocalArgumentDefinition { + kind: string; + name: string; + type: string; + defaultValue: any; +} + +export interface NormalizationModuleImport { + kind: string; + documentName: string; + fragmentPropName: string; + fragmentName: string; +} + export interface NormalizationLocalArgument { readonly kind: string; // 'LocalArgument'; readonly name: string; diff --git a/types/relay-runtime/lib/util/ReaderNode.d.ts b/types/relay-runtime/lib/util/ReaderNode.d.ts index b7e8d1212f..286ed9d28b 100644 --- a/types/relay-runtime/lib/util/ReaderNode.d.ts +++ b/types/relay-runtime/lib/util/ReaderNode.d.ts @@ -162,3 +162,25 @@ export interface ReaderPaginationFragment extends ReaderFragment { }; }; } + +export interface ReaderConnection { + readonly kind: string; + readonly label: string; + readonly name: string; + readonly args: ReadonlyArray; + readonly edges: ReaderLinkedField; + readonly pageInfo: ReaderLinkedField; +} + +export interface ReaderInlineDataFragmentSpread { + readonly kind: string; + readonly name: string; + readonly selections: ReadonlyArray; +} + +export interface ReaderModuleImport { + readonly kind: string; + readonly documentName: string; + readonly fragmentPropName: string; + readonly fragmentName: string; +} diff --git a/types/relay-runtime/lib/util/RelayConcreteNode.d.ts b/types/relay-runtime/lib/util/RelayConcreteNode.d.ts index 756c00f13e..14772cc33b 100644 --- a/types/relay-runtime/lib/util/RelayConcreteNode.d.ts +++ b/types/relay-runtime/lib/util/RelayConcreteNode.d.ts @@ -18,7 +18,7 @@ export interface RequestParameters { readonly metadata: { [key: string]: unknown }; } -declare const RelayConcreteNode: { +export const RelayConcreteNode: { CONDITION: 'Condition'; CLIENT_EXTENSION: 'ClientExtension'; DEFER: 'Defer'; @@ -42,5 +42,3 @@ declare const RelayConcreteNode: { STREAM: 'Stream'; VARIABLE: 'Variable'; }; - -export default RelayConcreteNode; diff --git a/types/relay-runtime/lib/util/RelayFeatureFlags.d.ts b/types/relay-runtime/lib/util/RelayFeatureFlags.d.ts new file mode 100644 index 0000000000..d6dda2e4a7 --- /dev/null +++ b/types/relay-runtime/lib/util/RelayFeatureFlags.d.ts @@ -0,0 +1,8 @@ +export interface FeatureFlags { + ENABLE_VARIABLE_CONNECTION_KEY: boolean; + ENABLE_CONNECTION_RESOLVERS: boolean; + ENABLE_PARTIAL_RENDERING_DEFAULT: boolean; + USE_RECORD_SOURCE_MAP_IMPL: boolean; +} + +export const RelayFeatureFlags: FeatureFlags; diff --git a/types/relay-runtime/lib/util/RelayProfiler.d.ts b/types/relay-runtime/lib/util/RelayProfiler.d.ts new file mode 100644 index 0000000000..653c706dee --- /dev/null +++ b/types/relay-runtime/lib/util/RelayProfiler.d.ts @@ -0,0 +1,115 @@ +export type Handler = (name: string, callback: () => void) => void; +export type ProfileHandler = (name: string, state?: any) => (error?: Error) => void; + +/** + * Instruments methods to allow profiling various parts of Relay. Profiling code + * in Relay consists of three steps: + * + * - Instrument the function to be profiled. + * - Attach handlers to the instrumented function. + * - Run the code which triggers the handlers. + * + * Handlers attached to instrumented methods are called with an instrumentation + * name and a callback that must be synchronously executed: + * + * instrumentedMethod.attachHandler(function(name, callback) { + * const start = performance.now(); + * callback(); + * console.log('Duration', performance.now() - start); + * }); + * + * Handlers for profiles are callbacks that return a stop method: + * + * RelayProfiler.attachProfileHandler('profileName', (name, state) => { + * const start = performance.now(); + * return function stop(name, state) { + * console.log(`Duration (${name})`, performance.now() - start); + * } + * }); + * + * In order to reduce the impact on performance in production, instrumented + * methods and profilers with names that begin with `@` will only be measured + * if `__DEV__` is true. This should be used for very hot functions. + */ + +export const RelayProfiler: { + /** + * Instruments methods on a class or object. This re-assigns the method in + * order to preserve function names in stack traces (which are detected by + * modern debuggers via heuristics). Example usage: + * + * const RelayStore = { primeCache: function() {...} }; + * RelayProfiler.instrumentMethods(RelayStore, { + * primeCache: 'RelayStore.primeCache' + * }); + * + * RelayStore.primeCache.attachHandler(...); + * + * As a result, the methods will be replaced by wrappers that provide the + * `attachHandler` and `detachHandler` methods. + */ + instrumentMethods(object: () => void | object, names: { [key: string]: string }): void; + + /** + * Wraps the supplied function with one that provides the `attachHandler` and + * `detachHandler` methods. Example usage: + * + * const printRelayQuery = + * RelayProfiler.instrument('printRelayQuery', printRelayQuery); + * + * printRelayQuery.attachHandler(...); + * + * NOTE: The instrumentation assumes that no handlers are attached or detached + * in the course of executing another handler. + */ + instrument void>(name: string, originalFunction: T): T; + + /** + * Attaches a handler to all methods instrumented with the supplied name. + * + * function createRenderer() { + * return RelayProfiler.instrument('render', function() {...}); + * } + * const renderA = createRenderer(); + * const renderB = createRenderer(); + * + * // Only profiles `renderA`. + * renderA.attachHandler(...); + * + * // Profiles both `renderA` and `renderB`. + * RelayProfiler.attachAggregateHandler('render', ...); + * + */ + attachAggregateHandler(name: string, handler: Handler): void; + + /** + * Detaches a handler attached via `attachAggregateHandler`. + */ + detachAggregateHandler(name: string, handler: Handler): void; + + /** + * Instruments profiling for arbitrarily asynchronous code by a name. + * + * const timerProfiler = RelayProfiler.profile('timeout'); + * setTimeout(function() { + * timerProfiler.stop(); + * }, 1000); + * + * RelayProfiler.attachProfileHandler('timeout', ...); + * + * Arbitrary state can also be passed into `profile` as a second argument. The + * attached profile handlers will receive this as the second argument. + */ + profile(name: string, state?: any): { stop: (error?: Error) => void }; + + /** + * Attaches a handler to profiles with the supplied name. You can also + * attach to the special name '*' which is a catch all. + */ + attachProfileHandler(name: string, handler: ProfileHandler): void; + + /** + * Detaches a handler attached via `attachProfileHandler`. + */ + detachProfileHandler(name: string, handler: ProfileHandler): void; +}; diff --git a/types/relay-runtime/lib/util/RelayRuntimeTypes.d.ts b/types/relay-runtime/lib/util/RelayRuntimeTypes.d.ts new file mode 100644 index 0000000000..72a42b1afb --- /dev/null +++ b/types/relay-runtime/lib/util/RelayRuntimeTypes.d.ts @@ -0,0 +1,41 @@ +/** + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ +export interface Disposable { + dispose(): void; +} + +export type DataID = string; + +// Variables +export interface Variables { + [name: string]: any; +} + +export interface OperationType { + readonly variables: Variables; + readonly response: unknown; +} + +/** + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + * in milliseconds. (This value will be passed to setTimeout.) + * - `liveConfigId`: causes a query to live update by calling GraphQLLiveQuery, + * it represents a configuration of gateway when doing live query + * - `metadata`: user-supplied metadata. + * - `transactionId`: a user-supplied value, intended for use as a unique id for + * a given instance of executing an operation. + */ +export interface CacheConfig { + force?: boolean | null; + poll?: number | null; + liveConfigId?: string | null; + metadata?: { [key: string]: unknown }; + transactionId?: string | null; +} diff --git a/types/relay-runtime/lib/util/deepFreeze.d.ts b/types/relay-runtime/lib/util/deepFreeze.d.ts new file mode 100644 index 0000000000..e9fa681325 --- /dev/null +++ b/types/relay-runtime/lib/util/deepFreeze.d.ts @@ -0,0 +1 @@ +export function deepFreeze(value: T): T; diff --git a/types/relay-runtime/lib/util/getRequestIdentifier.d.ts b/types/relay-runtime/lib/util/getRequestIdentifier.d.ts new file mode 100644 index 0000000000..af69f07cce --- /dev/null +++ b/types/relay-runtime/lib/util/getRequestIdentifier.d.ts @@ -0,0 +1,10 @@ +import { RequestParameters } from './RelayConcreteNode'; +import { Variables } from './RelayRuntimeTypes'; + +export type RequestIdentifier = string; + +/** + * Returns a stable identifier for the given pair of `RequestParameters` + + * variables. + */ +export function getRequestIdentifier(parameters: RequestParameters, variables: Variables): RequestIdentifier; diff --git a/types/relay-runtime/relay-runtime-tests.tsx b/types/relay-runtime/relay-runtime-tests.tsx index 8fedf058dc..27fcafbbc0 100644 --- a/types/relay-runtime/relay-runtime-tests.tsx +++ b/types/relay-runtime/relay-runtime-tests.tsx @@ -5,12 +5,12 @@ import { RecordSource, Store, ConnectionHandler, - ViewerHandler, commitLocalUpdate, QueryResponseCache, ROOT_ID, RelayNetworkLoggerTransaction, createRelayNetworkLogger, + RecordSourceSelectorProxy, } from 'relay-runtime'; const source = new RecordSource(); @@ -66,6 +66,16 @@ function handlerProvider(handle: any) { throw new Error(`handlerProvider: No handler provided for ${handle}`); } +function storeUpdater(store: RecordSourceSelectorProxy) { + const mutationPayload = store.getRootField('sendConversationMessage'); + const newMessageEdge = mutationPayload.getLinkedRecord('messageEdge'); + const conversationStore = store.get('a-conversation-id'); + const connection = ConnectionHandler.getConnection(conversationStore, 'Messages_messages'); + if (connection) { + ConnectionHandler.insertEdgeBefore(connection, newMessageEdge); + } +} + // ~~~~~~~~~~~~~~~~~~~~~ // Source // ~~~~~~~~~~~~~~~~~~~~~ @@ -77,7 +87,7 @@ store.publish(source); // ~~~~~~~~~~~~~~~~~~~~~ commitLocalUpdate(environment, store => { - const root = store.get(ROOT_ID)!; + const root = store.get(ROOT_ID); root.setValue('foo', 'localKey'); }); diff --git a/types/sauronjs/core/broadcast.d.ts b/types/sauronjs/core/broadcast.d.ts new file mode 100644 index 0000000000..7d9d701f6a --- /dev/null +++ b/types/sauronjs/core/broadcast.d.ts @@ -0,0 +1,8 @@ +import { Subscription } from 'rxjs/Subscription'; + +import Service = require('./service'); + +declare function next(channels: ReadonlyArray, event: string, data: any, id: string): void; +declare function attachSubject(object: Service): Subscription; + +export { next, attachSubject }; diff --git a/types/sauronjs/core/cache.d.ts b/types/sauronjs/core/cache.d.ts new file mode 100644 index 0000000000..fcf8654e34 --- /dev/null +++ b/types/sauronjs/core/cache.d.ts @@ -0,0 +1,17 @@ +declare class Cache { + constructor(); + get(key: string): any; + exists(key: string): boolean; + set(key: string, value: any): void; + clear(): void; + keys(): string[]; + size(): number; + forEach(fn: (key: string, value: any) => void): void; +} + +declare const CacheFactory: { + (id: string): Cache; + (): void; +}; + +export = CacheFactory; diff --git a/types/sauronjs/core/component.d.ts b/types/sauronjs/core/component.d.ts new file mode 100644 index 0000000000..1f1cd87fda --- /dev/null +++ b/types/sauronjs/core/component.d.ts @@ -0,0 +1,24 @@ +import { Observable } from 'rxjs/Observable'; +import { Subscription } from 'rxjs/Subscription'; + +interface ComponentParameters { + element: HTMLElement; + state?: any; +} + +declare class Component { + constructor(params: ComponentParameters); + + static _index: number; + + broadcast(event: string, data: any): void; + destroy(): void; + registerSubscription(subscriptions: ReadonlyArray): void; + subscribe(observables: ReadonlyArray>): void; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + attr(key: string): string; + attr(key: string, value: string): void; +} + +export = Component; diff --git a/types/sauronjs/core/index.d.ts b/types/sauronjs/core/index.d.ts new file mode 100644 index 0000000000..630d7ebdb2 --- /dev/null +++ b/types/sauronjs/core/index.d.ts @@ -0,0 +1,8 @@ +import CacheFactory = require('./cache'); +import Component = require('./component'); +import instance = require('./sauron'); +import Service = require('./service'); + +export { next, attachSubject } from './broadcast'; + +export { CacheFactory as cache, Component, instance, Service }; diff --git a/types/sauronjs/core/sauron.d.ts b/types/sauronjs/core/sauron.d.ts new file mode 100644 index 0000000000..7a7a6afd53 --- /dev/null +++ b/types/sauronjs/core/sauron.d.ts @@ -0,0 +1,22 @@ +import Component = require('./component'); +import Service = require('./service'); + +declare class Info { + total: number; +} + +interface SauronComponentMap { + [key: string]: Component; +} + +interface SauronInstance { + rebootstrap: (map?: SauronComponentMap) => void; + info: () => Info; + plugin: (plugin: (instance: SauronInstance, options: any) => void, options: any) => SauronInstance; + service: (Service: new (options: any) => Service, options: any) => SauronInstance; + initCache: (id: string) => void; +} + +declare function instance(componentMap: SauronComponentMap, id?: string): SauronInstance; + +export = instance; diff --git a/types/sauronjs/core/service.d.ts b/types/sauronjs/core/service.d.ts new file mode 100644 index 0000000000..4c362caf68 --- /dev/null +++ b/types/sauronjs/core/service.d.ts @@ -0,0 +1,9 @@ +declare class Service { + broadcastSubject: any; + + constructor(pubs: ReadonlyArray, subs: ReadonlyArray); + + broadcast(event: string, data: any): void; +} + +export = Service; diff --git a/types/sauronjs/index.d.ts b/types/sauronjs/index.d.ts new file mode 100644 index 0000000000..afa13f8ca1 --- /dev/null +++ b/types/sauronjs/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for sauronjs 0.1 +// Project: https://github.com/Fullscript/sauronjs +// Definitions by: EricPMulligan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.1 + +import * as util from './util'; +export { cache, Component, instance, next, Service } from './core'; + +export namespace events { + namespace dom { + function update(): void; + } +} + +export { util }; diff --git a/types/sauronjs/package.json b/types/sauronjs/package.json new file mode 100644 index 0000000000..6db59e2d67 --- /dev/null +++ b/types/sauronjs/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rxjs": "~5.5.0" + } +} diff --git a/types/sauronjs/sauronjs-tests.ts b/types/sauronjs/sauronjs-tests.ts new file mode 100644 index 0000000000..ea2fa22d4c --- /dev/null +++ b/types/sauronjs/sauronjs-tests.ts @@ -0,0 +1,37 @@ +import { cache, Component, events, instance, util, Service } from 'sauronjs'; + +events.dom.update(); + +// $ExpectType Component +new Component({ element: new HTMLElement() }); + +class SomeComponent extends Component {} + +// $ExpectType SomeComponent +const example = new SomeComponent({ element: new HTMLElement() }); + +util.insert(new HTMLElement()); +util.ready(() => { + 'example'; +}); + +// $ExpectType Service +new Service(['examplePublisher'], ['exampleSubscription']); + +class ExampleService extends Service { + constructor() { + super(['examplePublisher'], ['exampleSubscription']); + } +} + +// $ExpectType ExampleService +new ExampleService(); + +// $ExpectType Cache +cache('test'); + +// $ExpectType void +cache(); + +// $ExpectType SauronInstance +instance({ example }); diff --git a/types/sauronjs/tsconfig.json b/types/sauronjs/tsconfig.json new file mode 100644 index 0000000000..5806fe2aa4 --- /dev/null +++ b/types/sauronjs/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "esModuleInterop": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sauronjs-tests.ts" + ] +} diff --git a/types/sauronjs/tslint.json b/types/sauronjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sauronjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sauronjs/util/index.d.ts b/types/sauronjs/util/index.d.ts new file mode 100644 index 0000000000..05f519140d --- /dev/null +++ b/types/sauronjs/util/index.d.ts @@ -0,0 +1,4 @@ +import insert = require('./insert'); +import ready = require('./ready'); + +export { insert, ready }; diff --git a/types/sauronjs/util/insert.d.ts b/types/sauronjs/util/insert.d.ts new file mode 100644 index 0000000000..90bffe4d70 --- /dev/null +++ b/types/sauronjs/util/insert.d.ts @@ -0,0 +1,2 @@ +declare function insert(params: HTMLElement): void; +export = insert; diff --git a/types/sauronjs/util/ready.d.ts b/types/sauronjs/util/ready.d.ts new file mode 100644 index 0000000000..cb81e81c09 --- /dev/null +++ b/types/sauronjs/util/ready.d.ts @@ -0,0 +1,2 @@ +declare function ready(fn: () => void): void; +export = ready; diff --git a/types/serverless/classes/Plugin.d.ts b/types/serverless/classes/Plugin.d.ts index f9b85e29a0..99f1ab5db8 100644 --- a/types/serverless/classes/Plugin.d.ts +++ b/types/serverless/classes/Plugin.d.ts @@ -1,11 +1,32 @@ -import Serverless = require("../index"); +import Serverless = require('../index'); + +declare namespace Plugin { + interface Hooks { + [event: string]: (...rest: any[]) => any; + } + + interface Commands { + [command: string]: { + usage?: string; + lifecycleEvents?: string[]; + commands?: { [command: string]: {} }; + options?: { + [option: string]: { + usage?: string; + required?: boolean; + shortcut?: string; + }; + }; + }; + } +} declare abstract class Plugin { - hooks: { - [event: string]: Promise; - }; + hooks: Plugin.Hooks; - constructor(serverless: Serverless, options: Serverless.Options) + commands?: Plugin.Commands; + + constructor(serverless: Serverless, options: Serverless.Options); } export = Plugin; diff --git a/types/serverless/index.d.ts b/types/serverless/index.d.ts index d720ec2382..f7a0f81ca3 100644 --- a/types/serverless/index.d.ts +++ b/types/serverless/index.d.ts @@ -2,14 +2,15 @@ // Project: https://github.com/serverless/serverless#readme // Definitions by: Hassan Khan // Jonathan M. Wilbur +// Alex Pavlenko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import Service = require("./classes/Service"); -import Plugin = require("./classes/Plugin"); -import PluginManager = require("./classes/PluginManager"); -import Utils = require("./classes/Utils"); -import YamlParser = require("./classes/YamlParser"); -import AwsProvider = require("./plugins/aws/provider/awsProvider"); +import Service = require('./classes/Service'); +import Plugin = require('./classes/Plugin'); +import PluginManager = require('./classes/PluginManager'); +import Utils = require('./classes/Utils'); +import YamlParser = require('./classes/YamlParser'); +import AwsProvider = require('./plugins/aws/provider/awsProvider'); declare namespace Serverless { interface Options { @@ -32,7 +33,7 @@ declare namespace Serverless { handler: string; timeout?: number; memorySize?: number; - environment?: { [ name: string ]: string }; + environment?: { [name: string]: string }; } interface Event { diff --git a/types/serverless/serverless-tests.ts b/types/serverless/serverless-tests.ts index ae5941e5ee..002f9e98d2 100644 --- a/types/serverless/serverless-tests.ts +++ b/types/serverless/serverless-tests.ts @@ -1,9 +1,37 @@ import Serverless from 'serverless'; +import Plugin from 'serverless/classes/Plugin'; const options: Serverless.Options = { noDeploy: false, stage: null, - region: '' + region: '', }; const serverless = new Serverless(); + +class CustomPlugin extends Plugin { + commands = { + command: { + usage: 'description', + lifecycleEvents: ['start'], + options: { + option: { + usage: `description`, + required: true, + shortcut: 'o', + }, + }, + }, + }; + + customProp = {}; + + hooks: Plugin.Hooks; + + constructor(serverless: Serverless, options: Serverless.Options) { + super(serverless, options); + this.hooks = { + 'command:start': () => {}, + }; + } +} diff --git a/types/signalfx/index.d.ts b/types/signalfx/index.d.ts new file mode 100644 index 0000000000..77c4b040cd --- /dev/null +++ b/types/signalfx/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for signalfx 7.0 +// Project: https://github.com/signalfx/signalfx-nodejs +// Definitions by: Vladimir Grenaderov +// Max Boguslavskiy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export interface IngestOptions { + enableAmazonUniqueId?: boolean; + dimensions?: object; + ingestEndpoint?: string; + timeout?: number; + batchSize?: number; + userAgents?: string[]; + proxy?: string; +} + +export interface SignalMetric { + metric: string; + value: number; + timestamp?: number; +} + +export interface SignalReport { + cumulative_counters?: SignalMetric[]; + gauges?: SignalMetric[]; + counters?: SignalMetric[]; +} + +export interface SignalClient { + send(report: SignalReport): void; +} + +export class Ingest { + constructor(token: string, options?: IngestOptions); + send(report: SignalReport): void; +} + +export class IngestJson { + constructor(token: string, options?: IngestOptions); + send(report: SignalReport): void; +} + +export const CONSTANTS: { + MESSAGE_TYPES: { + CONTROL: string; + DATA: string; + EVENT: string; + METADATA: string; + }; +}; + +export function SignalFlow(apiToken: any, options: any): any; diff --git a/types/signalfx/signalfx-tests.ts b/types/signalfx/signalfx-tests.ts new file mode 100644 index 0000000000..8c1b218e9c --- /dev/null +++ b/types/signalfx/signalfx-tests.ts @@ -0,0 +1,4 @@ +import * as signalfx from 'signalfx'; + +const sgnlfx = new signalfx.Ingest('1'); +sgnlfx.send({}); diff --git a/types/signalfx/tsconfig.json b/types/signalfx/tsconfig.json new file mode 100644 index 0000000000..5c9c420829 --- /dev/null +++ b/types/signalfx/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "signalfx-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/signalfx/tslint.json b/types/signalfx/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/signalfx/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/svgo/index.d.ts b/types/svgo/index.d.ts index 43eeff6654..f3d83ae944 100644 --- a/types/svgo/index.d.ts +++ b/types/svgo/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for svgo 1.2 +// Type definitions for svgo 1.3 // Project: https://github.com/svg/svgo // Definitions by: Bradley Ayers // Gilad Gray // Aankhen // Jan Karres +// Gavin Gregory // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -201,7 +202,11 @@ interface SvgInfo { interface OptimizedSvg { data: string; - info: object; + info: { + width: string; + height: string; + }; + path?: string; } declare class SVGO { diff --git a/types/svgo/svgo-tests.ts b/types/svgo/svgo-tests.ts index c06e6d61a5..84bdf1297d 100644 --- a/types/svgo/svgo-tests.ts +++ b/types/svgo/svgo-tests.ts @@ -27,5 +27,16 @@ const options: SVGO.Options = { svgo = new SVGO(options); // SVGO instance methods -svgo.optimize(``, { path: "filepath" }) - .then(result => result.data, error => error); +svgo + .optimize(``, { + path: 'filepath', + }) + .then( + result => { + result.data; + result.info.height; + result.info.width; + result.path; + }, + error => error, + ); diff --git a/types/typography-breakpoint-constants/index.d.ts b/types/typography-breakpoint-constants/index.d.ts new file mode 100644 index 0000000000..d785b99258 --- /dev/null +++ b/types/typography-breakpoint-constants/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for typography-breakpoint-constants 0.16 +// Project: https://github.com/KyleAMathews/typography.js +// Definitions by: Luis Rodrigues +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const DEFAULT_MEDIA_QUERY: string; +export const DEFAULT_WIDTH: string; +export const LARGER_DISPLAY_MEDIA_QUERY: string; +export const LARGER_DISPLAY_WIDTH: string; +export const LARGE_DISPLAY_MEDIA_QUERY: string; +export const LARGE_DISPLAY_WIDTH: string; +export const MIN_DEFAULT_MEDIA_QUERY: string; +export const MIN_LARGER_DISPLAY_MEDIA_QUERY: string; +export const MIN_LARGE_DISPLAY_MEDIA_QUERY: string; +export const MIN_MOBILE_MEDIA_QUERY: string; +export const MIN_TABLET_MEDIA_QUERY: string; +export const MOBILE_MEDIA_QUERY: string; +export const MOBILE_WIDTH: string; +export const TABLET_MEDIA_QUERY: string; +export const TABLET_WIDTH: string; diff --git a/types/typography-breakpoint-constants/tsconfig.json b/types/typography-breakpoint-constants/tsconfig.json new file mode 100644 index 0000000000..f7dd7b9d27 --- /dev/null +++ b/types/typography-breakpoint-constants/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "typography-breakpoint-constants-tests.ts" + ] +} diff --git a/types/typography-breakpoint-constants/tslint.json b/types/typography-breakpoint-constants/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/typography-breakpoint-constants/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/typography-breakpoint-constants/typography-breakpoint-constants-tests.ts b/types/typography-breakpoint-constants/typography-breakpoint-constants-tests.ts new file mode 100644 index 0000000000..1aaa5739c9 --- /dev/null +++ b/types/typography-breakpoint-constants/typography-breakpoint-constants-tests.ts @@ -0,0 +1,35 @@ +import { + DEFAULT_MEDIA_QUERY, + DEFAULT_WIDTH, + LARGER_DISPLAY_MEDIA_QUERY, + LARGER_DISPLAY_WIDTH, + LARGE_DISPLAY_MEDIA_QUERY, + LARGE_DISPLAY_WIDTH, + MIN_DEFAULT_MEDIA_QUERY, + MIN_LARGER_DISPLAY_MEDIA_QUERY, + MIN_LARGE_DISPLAY_MEDIA_QUERY, + MIN_MOBILE_MEDIA_QUERY, + MIN_TABLET_MEDIA_QUERY, + MOBILE_MEDIA_QUERY, + MOBILE_WIDTH, + TABLET_MEDIA_QUERY, + TABLET_WIDTH, +} from 'typography-breakpoint-constants'; + +function testString(value: string): void {} + +testString(DEFAULT_MEDIA_QUERY); +testString(DEFAULT_WIDTH); +testString(LARGER_DISPLAY_MEDIA_QUERY); +testString(LARGER_DISPLAY_WIDTH); +testString(LARGE_DISPLAY_MEDIA_QUERY); +testString(LARGE_DISPLAY_WIDTH); +testString(MIN_DEFAULT_MEDIA_QUERY); +testString(MIN_LARGER_DISPLAY_MEDIA_QUERY); +testString(MIN_LARGE_DISPLAY_MEDIA_QUERY); +testString(MIN_MOBILE_MEDIA_QUERY); +testString(MIN_TABLET_MEDIA_QUERY); +testString(MOBILE_MEDIA_QUERY); +testString(MOBILE_WIDTH); +testString(TABLET_MEDIA_QUERY); +testString(TABLET_WIDTH); diff --git a/types/unused-files-webpack-plugin/index.d.ts b/types/unused-files-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..8656e7b8a2 --- /dev/null +++ b/types/unused-files-webpack-plugin/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for unused-files-webpack-plugin 3.4 +// Project: https://github.com/tomchentw/unused-files-webpack-plugin +// Definitions by: Vladimir Grenaderov +// Max Boguslavskiy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; + +export interface Options { + patterns?: string[]; + failOnUnused: boolean; + globOptions?: { + ignore?: string | string[]; + }; + ignore?: string | string[]; + cwd?: string; +} + +export class UnusedFilesWebpackPlugin extends Plugin { + constructor(options: Options); +} diff --git a/types/unused-files-webpack-plugin/tsconfig.json b/types/unused-files-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..0307cf1ede --- /dev/null +++ b/types/unused-files-webpack-plugin/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", + "unused-files-webpack-plugin-tests.ts" + ] +} diff --git a/types/unused-files-webpack-plugin/tslint.json b/types/unused-files-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unused-files-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unused-files-webpack-plugin/unused-files-webpack-plugin-tests.ts b/types/unused-files-webpack-plugin/unused-files-webpack-plugin-tests.ts new file mode 100644 index 0000000000..71313e1a37 --- /dev/null +++ b/types/unused-files-webpack-plugin/unused-files-webpack-plugin-tests.ts @@ -0,0 +1,29 @@ +import * as webpack from 'webpack'; +import { UnusedFilesWebpackPlugin } from 'unused-files-webpack-plugin'; + +const ignoredFiles = ['']; +const config: webpack.Configuration = { + plugins: [ + new UnusedFilesWebpackPlugin({ + failOnUnused: false, + }), + new UnusedFilesWebpackPlugin({ + failOnUnused: true, + globOptions: { + ignore: ignoredFiles, + }, + }), + new UnusedFilesWebpackPlugin({ + patterns: ['one', 'two'], + failOnUnused: true, + }), + new UnusedFilesWebpackPlugin({ + failOnUnused: false, + ignore: 'no', + }), + new UnusedFilesWebpackPlugin({ + failOnUnused: false, + cwd: 'cwd', + }), + ], +}; diff --git a/types/use-combined-reducers/index.d.ts b/types/use-combined-reducers/index.d.ts new file mode 100644 index 0000000000..9505bcd9f0 --- /dev/null +++ b/types/use-combined-reducers/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for use-combined-reducers 1.0 +// Project: https://github.com/the-road-to-learn-react/use-combined-reducers#readme +// Definitions by: kwdowik +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export default function useCombinedReducers(combinedReducers: Record]>): [T, (action: A) => void]; diff --git a/types/use-combined-reducers/tsconfig.json b/types/use-combined-reducers/tsconfig.json new file mode 100644 index 0000000000..fe5c1472ae --- /dev/null +++ b/types/use-combined-reducers/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "use-combined-reducers-tests.ts" + ] +} diff --git a/types/use-combined-reducers/tslint.json b/types/use-combined-reducers/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/use-combined-reducers/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/use-combined-reducers/use-combined-reducers-tests.ts b/types/use-combined-reducers/use-combined-reducers-tests.ts new file mode 100644 index 0000000000..d8e825baf8 --- /dev/null +++ b/types/use-combined-reducers/use-combined-reducers-tests.ts @@ -0,0 +1,6 @@ +import useCombinedReducers from 'use-combined-reducers'; + +useCombinedReducers<{ a: number; b: any }, () => {}>({ + a: ['', () => { }], + b: ['', () => { }], +}); diff --git a/types/use-global-hook/index.d.ts b/types/use-global-hook/index.d.ts index 266a426a15..19ad7e56a8 100644 --- a/types/use-global-hook/index.d.ts +++ b/types/use-global-hook/index.d.ts @@ -23,4 +23,4 @@ export default function useStore( inititalState: S, actions: object, initializers?: InitializerFunction, -): () => [S, A]; +): (stateFunc?: (state: S) => NS, actionsFunc?: (state: A) => NA) => [NS, NA]; diff --git a/types/use-global-hook/use-global-hook-tests.ts b/types/use-global-hook/use-global-hook-tests.ts index e13973e83e..c2ceaaa05e 100644 --- a/types/use-global-hook/use-global-hook-tests.ts +++ b/types/use-global-hook/use-global-hook-tests.ts @@ -1,13 +1,28 @@ import useStore, { Store, InitializerFunction } from 'use-global-hook'; import React = require('react'); -interface state { value: string; } -interface associatedActions { setValue(value: string): void; } -const initializer: InitializerFunction = (store: Store) => { - store.actions.setValue(""); +interface stateType { + value: string; +} + +type setFunc = (value: string) => void; + +interface associatedActionsType { + setValue: setFunc; +} + +const initializer: InitializerFunction = (store: Store) => { + store.actions.setValue(''); store.state.value; - store.setState({ value: "string" }); + store.setState({ value: 'string' }); }; -useStore(React, { value: "" }, {}, initializer); // $ExpectType () => [state, associatedActions] -useStore(React, { value: "" }, {}); // $ExpectType () => [state, associatedActions] +const store = useStore(React, { value: '' }, {}, initializer); + +store(); // $ExpectType [unknown, unknown] +store(); // $ExpectType [stateType, associatedActionsType] +store((state: stateType) => state.value); // $ExpectType [string, associatedActionsType] +store(undefined, (action: associatedActionsType) => action.setValue); // $ExpectType [stateType, setFunc] +store((state: stateType) => state.value, (actions: associatedActionsType) => actions.setValue); // $ExpectType [string, setFunc] + +useStore(React, { value: '' }, {}); diff --git a/types/workerpool/index.d.ts b/types/workerpool/index.d.ts index c8a128203b..2bb6ca4b66 100644 --- a/types/workerpool/index.d.ts +++ b/types/workerpool/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for workerpool 3.1 +// Type definitions for workerpool 5.0 // Project: https://github.com/josdejong/workerpool // Definitions by: Alorel // Seulgi Kim @@ -96,9 +96,21 @@ export interface WorkerPoolOptions { * In case of 'process' (default), child_process will be used. * In case of 'thread', worker_threads will be used. If worker_threads are not available, an error is thrown. * In case of 'auto', worker_threads will be used if available (Node.js >= 11.7.0), else child_process will be used as fallback. + * @deprecated */ nodeWorker?: 'process' | 'thread' | 'auto'; + /** + * - In case of `'auto'` (default), workerpool will automatically pick a suitable type of worker: + * when in a browser environment, `'web'` will be used. When in a node.js environment, `worker_threads` will be used + * if available (Node.js >= 11.7.0), else `child_process` will be used. + * - In case of `'web'`, a Web Worker will be used. Only available in a browser environment. + * - In case of `'process'`, `child_process` will be used. Only available in a node.js environment. + * - In case of `'thread'`, `worker_threads` will be used. If `worker_threads` are not available, an error is thrown. + * Only available in a node.js environment. + */ + workerType?: 'auto' | 'web' | 'process' | 'thread'; + /** 2nd argument to pass to childProcess.fork() */ forkArgs?: string[]; @@ -106,9 +118,11 @@ export interface WorkerPoolOptions { } /** - * When a script argument is provided, the provided script will be started as a dedicated worker. - * When no script argument is provided, a default worker is started which can be used to offload functions dynamically via Pool.exec. - * Note that on node.js, script must be an absolute file path like __dirname + '/myWorker.js'. + * When a `script` argument is provided, the provided script will be started as a dedicated worker. + * When no `script` argument is provided, a default worker is started which can be used to offload functions dynamically via `Pool.exec`. + * Note that on node.js, `script` must be an absolute file path like `__dirname + '/myWorker.js'`. + * In a browser environment, `script` can also be a data URL like `'data:application/javascript;base64,...'`. + * This allows embedding the bundled code of a worker in your main application. See `examples/embeddedWorker` for a demo. */ export function pool(pathToScript?: string, options?: WorkerPoolOptions): WorkerPool; diff --git a/types/workerpool/workerpool-tests.ts b/types/workerpool/workerpool-tests.ts index dc75955479..b1d3c38c4d 100644 --- a/types/workerpool/workerpool-tests.ts +++ b/types/workerpool/workerpool-tests.ts @@ -9,6 +9,10 @@ wp.pool({maxWorkers: 1}); wp.pool({nodeWorker: 'process'}); wp.pool({nodeWorker: 'thread'}); wp.pool({nodeWorker: 'auto'}); +wp.pool({workerType: 'process'}); +wp.pool({workerType: 'thread'}); +wp.pool({workerType: 'web'}); +wp.pool({workerType: 'auto'}); wp.pool({forkArgs: ['foo', 'bar']}); wp.pool({forkOpts: {cwd: '/tmp'}}); const pool = wp.pool(); diff --git a/types/xml-c14n/index.d.ts b/types/xml-c14n/index.d.ts new file mode 100644 index 0000000000..5ac65b05e3 --- /dev/null +++ b/types/xml-c14n/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for xml-c14n 0.0 +// Project: https://github.com/deoxxa/xml-c14n +// Definitions by: Konstantin Yuriev +// Max Boguslavskiy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +declare namespace xml_c14n { + type canonicaliseCb = (err: any, data: string) => void; + + interface Options { + includeComments?: boolean; + inclusiveNamespaces?: boolean; + } + + interface Canonicalize { + name(): string; + _processInner(node: Node): string; + canonicalise(node: Node, cb: canonicaliseCb): void; + } + + interface CanonizationFactory { + createCanonicaliser(kind: string, options?: Options): Canonicalize; + getAlgorithm(uri: string): any; + registerAlgorithm(uri: string, implementation: any): any; + } +} + +declare function xml_c14n(): xml_c14n.CanonizationFactory; + +export = xml_c14n; diff --git a/types/xml-c14n/tsconfig.json b/types/xml-c14n/tsconfig.json new file mode 100644 index 0000000000..bee18a373b --- /dev/null +++ b/types/xml-c14n/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "esModuleInterop": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "xml-c14n-tests.ts" + ] +} diff --git a/types/xml-c14n/tslint.json b/types/xml-c14n/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/xml-c14n/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/xml-c14n/xml-c14n-tests.ts b/types/xml-c14n/xml-c14n-tests.ts new file mode 100644 index 0000000000..850e0c6aa1 --- /dev/null +++ b/types/xml-c14n/xml-c14n-tests.ts @@ -0,0 +1,5 @@ +import c14n from 'xml-c14n'; + +const canonizer = c14n().createCanonicaliser( + 'http://www.w3.org/2001/10/xml-exc-c14n#', +);