From 5380cf2a252452830789e2951fe2ee4ef791d5d1 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Wed, 5 Dec 2018 11:15:50 +0100 Subject: [PATCH 001/225] Copy mongoose-paginate declaration to mongoose-paginate-v2. --- types/mongoose-paginate-v2/index.d.ts | 51 ++++++++++++ .../mongoose-paginate-tests.ts | 71 +++++++++++++++++ types/mongoose-paginate-v2/tsconfig.json | 23 ++++++ types/mongoose-paginate-v2/tslint.json | 79 +++++++++++++++++++ 4 files changed, 224 insertions(+) create mode 100644 types/mongoose-paginate-v2/index.d.ts create mode 100644 types/mongoose-paginate-v2/mongoose-paginate-tests.ts create mode 100644 types/mongoose-paginate-v2/tsconfig.json create mode 100644 types/mongoose-paginate-v2/tslint.json diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts new file mode 100644 index 0000000000..ad54786f53 --- /dev/null +++ b/types/mongoose-paginate-v2/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for mongoose-paginate 5.0.0 +// Project: https://github.com/edwardhotchkiss/mongoose-paginate +// Definitions by: Linus Brolin , simonxca +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +declare module 'mongoose' { + export interface PaginateOptions { + select?: Object | string; + sort?: Object | string; + populate?: Array | Array | Object | string; + lean?: boolean; + leanWithId?: boolean; + offset?: number; + page?: number; + limit?: number; + } + + export interface PaginateResult { + docs: Array; + total: number; + limit: number; + page?: number; + pages?: number; + offset?: number; + } + + interface PaginateModel extends Model { + paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; + } + + export function model( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean): PaginateModel; + + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean): U; +} + +declare module 'mongoose-paginate' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema) => void; + export = _; +} diff --git a/types/mongoose-paginate-v2/mongoose-paginate-tests.ts b/types/mongoose-paginate-v2/mongoose-paginate-tests.ts new file mode 100644 index 0000000000..d55f8a454e --- /dev/null +++ b/types/mongoose-paginate-v2/mongoose-paginate-tests.ts @@ -0,0 +1,71 @@ +/** + * Created by Linus Brolin . + */ + +import { + Schema, + model, + PaginateModel, + PaginateOptions, + PaginateResult, + Document +} from 'mongoose'; +import mongoosePaginate = require('mongoose-paginate'); +import { Router, Request, Response } from 'express'; + + +//#region Test Models +interface User extends Document { + email: string; + username: string; + password: string; +} + +const UserSchema: Schema = new Schema({ + email: String, + username: String, + password: String +}); + +UserSchema.plugin(mongoosePaginate); + +interface UserModel extends PaginateModel {}; + +let UserModel: UserModel = model('User', UserSchema) as UserModel; +//#endregion + + +//#region Test Paginate +let router: Router = Router(); + +router.get('/users.json', function(req: Request, res: Response) { + let descending: boolean = true; + let options: PaginateOptions = {} as PaginateOptions; + options.select = 'email username'; + options.sort = { 'username': (descending ? -1 : 1) }; + options.populate = ''; + options.lean = true; + options.leanWithId = false; + options.offset = 0; + options.page = 1; + options.limit = 10; + + UserModel + .paginate({}, options, (err: any, value: PaginateResult) => { + if (err) { + console.log(err); + return res.status(500).send(err); + } + + console.log('total: ' + value.total); + console.log('limit: ' + value.limit); + console.log('page: ' + value.page); + console.log('pages: ' + value.pages); + console.log('offset: ' + value.offset); + console.log('docs: '); + console.dir(value.docs); + return res.json(value); + }); + +}); +//#endregion diff --git a/types/mongoose-paginate-v2/tsconfig.json b/types/mongoose-paginate-v2/tsconfig.json new file mode 100644 index 0000000000..3194368f11 --- /dev/null +++ b/types/mongoose-paginate-v2/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mongoose-paginate-tests.ts" + ] +} \ No newline at end of file diff --git a/types/mongoose-paginate-v2/tslint.json b/types/mongoose-paginate-v2/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/mongoose-paginate-v2/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} From ad776bc550c59a14f387157c2ea1dc733790fe49 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Wed, 5 Dec 2018 11:40:07 +0100 Subject: [PATCH 002/225] Update declarations to correspond with mongoose-paginate-v2 module. --- types/mongoose-paginate-v2/index.d.ts | 23 ++++++++++++++++--- ...tests.ts => mongoose-paginate-v2-tests.ts} | 22 ++++++++++++++---- types/mongoose-paginate-v2/tsconfig.json | 4 ++-- 3 files changed, 39 insertions(+), 10 deletions(-) rename types/mongoose-paginate-v2/{mongoose-paginate-tests.ts => mongoose-paginate-v2-tests.ts} (68%) diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index ad54786f53..6c9103f852 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -1,15 +1,31 @@ -// Type definitions for mongoose-paginate 5.0.0 +// Type definitions for mongoose-paginate-v2 1.0.13 // Project: https://github.com/edwardhotchkiss/mongoose-paginate -// Definitions by: Linus Brolin , simonxca +// Definitions by: Linus Brolin +// simonxca +// woutgg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +// +// Based on type declarations for mongoose-paginate 5.0.0. /// declare module 'mongoose' { + export interface CustomLabels { + totalDocs?: string, + limit?: string, + page?: string, + totalPages?: string, + docs?: string, + nextPage?: string, + prevPage?: string, + } + export interface PaginateOptions { select?: Object | string; sort?: Object | string; + customLabels?: CustomLabels, + collation?: CollationOptions, populate?: Array | Array | Object | string; lean?: boolean; leanWithId?: boolean; @@ -25,6 +41,7 @@ declare module 'mongoose' { page?: number; pages?: number; offset?: number; + [customLabel: string]: Array | number | undefined; } interface PaginateModel extends Model { @@ -44,7 +61,7 @@ declare module 'mongoose' { skipInit?: boolean): U; } -declare module 'mongoose-paginate' { +declare module 'mongoose-paginate-v2' { import mongoose = require('mongoose'); var _: (schema: mongoose.Schema) => void; export = _; diff --git a/types/mongoose-paginate-v2/mongoose-paginate-tests.ts b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts similarity index 68% rename from types/mongoose-paginate-v2/mongoose-paginate-tests.ts rename to types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts index d55f8a454e..8410c740e5 100644 --- a/types/mongoose-paginate-v2/mongoose-paginate-tests.ts +++ b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts @@ -43,12 +43,22 @@ router.get('/users.json', function(req: Request, res: Response) { let options: PaginateOptions = {} as PaginateOptions; options.select = 'email username'; options.sort = { 'username': (descending ? -1 : 1) }; + options.collation = { locale: 'en_US', strength: 1 }; options.populate = ''; options.lean = true; options.leanWithId = false; options.offset = 0; options.page = 1; options.limit = 10; + options.customLabels = { + totalDocs: 'totalDocsCustom', + limit: 'limitCustom', + page: 'pageCustom', + totalPages: 'totalPagesCustom', + docs: 'docsCustom', + nextPage: 'nextPageCustom', + prevPage: 'prevPageCustom' + }; UserModel .paginate({}, options, (err: any, value: PaginateResult) => { @@ -57,13 +67,15 @@ router.get('/users.json', function(req: Request, res: Response) { return res.status(500).send(err); } - console.log('total: ' + value.total); - console.log('limit: ' + value.limit); - console.log('page: ' + value.page); - console.log('pages: ' + value.pages); + console.log('totalDocs: ' + value.totalDocsCustom); + console.log('limit: ' + value.limitCustom); + console.log('page: ' + value.pageCustom); + console.log('nextPage: ' + value.nextPageCustom); + console.log('prevPage: ' + value.prevPageCustom); + console.log('totalPages: ' + value.totalPagesCustom); console.log('offset: ' + value.offset); console.log('docs: '); - console.dir(value.docs); + console.dir(value.docsCustom); return res.json(value); }); diff --git a/types/mongoose-paginate-v2/tsconfig.json b/types/mongoose-paginate-v2/tsconfig.json index 3194368f11..1e367240a9 100644 --- a/types/mongoose-paginate-v2/tsconfig.json +++ b/types/mongoose-paginate-v2/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "mongoose-paginate-tests.ts" + "mongoose-paginate-v2-tests.ts" ] -} \ No newline at end of file +} From ef1ca953366b7decc3f553fc83afdd6cf72ae492 Mon Sep 17 00:00:00 2001 From: Tim Griesser Date: Tue, 11 Dec 2018 17:06:37 -0500 Subject: [PATCH 003/225] Remove global Express.Request.user declaration This should be defined by the consumer based on what they know the type might be, rather than by the type definitions --- types/express-jwt/index.d.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index 1187f4fbca..d1029849cc 100644 --- a/types/express-jwt/index.d.ts +++ b/types/express-jwt/index.d.ts @@ -58,10 +58,3 @@ declare namespace jwt { constructor(code: ErrorCode, error: { message: string }); } } -declare global { - namespace Express { - export interface Request { - user?: any - } - } -} From b8afa6b51d275d3902b34aa2fcc66c4fb87cbdb6 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Tue, 18 Dec 2018 07:57:24 +0100 Subject: [PATCH 004/225] Fix project URL. --- types/mongoose-paginate-v2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index 6c9103f852..242cbdcd9a 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for mongoose-paginate-v2 1.0.13 -// Project: https://github.com/edwardhotchkiss/mongoose-paginate +// Project: https://github.com/aravindnc/mongoose-paginate-v2 // Definitions by: Linus Brolin // simonxca // woutgg From a623516aa78e67b507e5135869f4404bd9f91ef6 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Mon, 24 Dec 2018 12:39:12 +0100 Subject: [PATCH 005/225] Remove model type parameter and overload. --- types/mongoose-paginate-v2/index.d.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index 242cbdcd9a..3c178c5908 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -48,17 +48,11 @@ declare module 'mongoose' { paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; } - export function model( + export function model( name: string, schema?: Schema, collection?: string, - skipInit?: boolean): PaginateModel; - - export function model>( - name: string, - schema?: Schema, - collection?: string, - skipInit?: boolean): U; + skipInit?: boolean): PaginateModel; } declare module 'mongoose-paginate-v2' { From e94a58fba1849dcc033ab433a4f213258a95651f Mon Sep 17 00:00:00 2001 From: PopGoesTheWza Date: Wed, 26 Dec 2018 15:30:12 +0100 Subject: [PATCH 006/225] GAS "December 13, 2018" update --- .../google-apps-script.base.d.ts | 18 +- .../google-apps-script.card-service.d.ts | 753 ++++++++++++++++++ .../google-apps-script.charts.d.ts | 18 +- .../google-apps-script.data-studio.d.ts | 301 +++++++ .../google-apps-script.forms.d.ts | 7 +- .../google-apps-script.gmail.d.ts | 3 +- .../google-apps-script.groups.d.ts | 8 +- .../google-apps-script.script.d.ts | 6 +- .../google-apps-script.slides.d.ts | 97 ++- .../google-apps-script.spreadsheet.d.ts | 135 +++- .../google-apps-script.utilities.d.ts | 15 +- 11 files changed, 1320 insertions(+), 41 deletions(-) create mode 100644 types/google-apps-script/google-apps-script.card-service.d.ts create mode 100644 types/google-apps-script/google-apps-script.data-studio.d.ts diff --git a/types/google-apps-script/google-apps-script.base.d.ts b/types/google-apps-script/google-apps-script.base.d.ts index 7558263306..0b5236af0f 100644 --- a/types/google-apps-script/google-apps-script.base.d.ts +++ b/types/google-apps-script/google-apps-script.base.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,7 @@ declare namespace GoogleAppsScript { export module Base { - /** + /** * A data interchange object for Apps Script services. */ export interface Blob { @@ -74,9 +74,10 @@ declare namespace GoogleAppsScript { } /** - * This class provides access to G Suite specific dialog boxes. + * This class provides access to dialog boxes specific to Google Sheets. * * The methods in this class are only available for use in the context of a Google Spreadsheet. + * Please use G Suite dialogs instead. * See also * * ButtonSet @@ -163,9 +164,9 @@ declare namespace GoogleAppsScript { /** * An enumeration that provides access to MIME-type declarations without typing the strings - * explicitly. Any method that expects a MIME type rendered as a string (for example, - * 'image/png') will also accept one of the values below, so long as the method - * supports the underlying MIME type. + * explicitly. Methods that expect a MIME type rendered as a string (for example, + * 'image/png') also accept any of the values below, so long as the method supports the + * underlying MIME type. * * // Use MimeType enum to log the name of every Google Doc in the user's Drive. * var docs = DriveApp.getFilesByType(MimeType.GOOGLE_DOCS); @@ -305,11 +306,15 @@ declare namespace GoogleAppsScript { * } */ export interface console { + error(): void; error(formatOrObject: Object, ...values: Object[]): void; + info(): void; info(formatOrObject: Object, ...values: Object[]): void; + log(): void; log(formatOrObject: Object, ...values: Object[]): void; time(label: string): void; timeEnd(label: string): void; + warn(): void; warn(formatOrObject: Object, ...values: Object[]): void; } @@ -321,3 +326,4 @@ declare var Logger: GoogleAppsScript.Base.Logger; // conflicts with MimeType in lib.d.ts // declare var MimeType: GoogleAppsScript.Base.MimeType; declare var Session: GoogleAppsScript.Base.Session; +declare var console: GoogleAppsScript.Base.console; diff --git a/types/google-apps-script/google-apps-script.card-service.d.ts b/types/google-apps-script/google-apps-script.card-service.d.ts new file mode 100644 index 0000000000..64f5194595 --- /dev/null +++ b/types/google-apps-script/google-apps-script.card-service.d.ts @@ -0,0 +1,753 @@ +// Type definitions for Google Apps Script 2018-12-26 +// Project: https://developers.google.com/apps-script/ +// Definitions by: motemen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GoogleAppsScript { + export module Card_Service { + /** + * An action that enables interactivity within UI elements. The action does not happen directly on + * the client but rather invokes an Apps Script callback function with optional parameters. + * + * var image = CardService.newImage() + * .setOnClickAction(CardService.newAction() + * .setFunctionName("handleImageClick") + * .setParameters({imageSrc: 'carImage'})); + */ + export interface Action { + setFunctionName(functionName: string): Action; + setLoadIndicator(loadIndicator: LoadIndicator): Action; + setParameters(parameters: Object): Action; + setMethodName(functionName: string): Action; + } + + /** + * The response object that may be returned from a callback function (e.g., a form response handler) + * to perform one or more actions on the client. Some combinations of actions are not supported. + * + * // An action that opens a link + * var actionResponse = CardService.newActionResponseBuilder() + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://www.google.com")) + * .build(); + * + * // An action that shows a notification. + * var actionResponse = CardService.newActionResponseBuilder() + * .setNotification(CardService.newNotification() + * .setType(CardService.NotificationType.INFO) + * .setText("Some info to display to user")) + * .build(); + * + * // An action that shows an additional card. It also sets a flag to indicate that the original + * // state data has changed. + * + * var cardBuilder = CardService.newCardBuilder(); + * // Build card ... + * var actionResponse = CardService.newActionResponseBuilder() + * .setNavigation(CardService.newNavigation() + * .pushCard(cardBuilder.build())) + * .setStateChanged(true) + * .build(); + */ + export interface ActionResponse { + printJson(): string; + } + + /** + * A builder for ActionResponse objects. + */ + export interface ActionResponseBuilder { + build(): ActionResponse; + setNavigation(navigation: Navigation): ActionResponseBuilder; + setNotification(notification: Notification): ActionResponseBuilder; + setOpenLink(openLink: OpenLink): ActionResponseBuilder; + setStateChanged(stateChanged: boolean): ActionResponseBuilder; + } + + /** + * An authorization action that will send the user to the AuthorizationUrl when clicked. + * + * CardService.newAuthorizationAction() + * .setAuthorizationUrl("http://google.com/"); + */ + export interface AuthorizationAction { + setAuthorizationUrl(authorizationUrl: string): AuthorizationAction; + } + + /** + * An error that can be returned to trigger an authorization card to be shown to the user. + * + * CardService.newAuthorizationException() + * .setAuthorizationUrl("http://auth.com/") + * .setResourceDisplayName("Example Resource") + * .throwException(); + */ + export interface AuthorizationException { + printJson(): string; + setAuthorizationUrl(authUrl: string): AuthorizationException; + setCustomUiCallback(callback: string): AuthorizationException; + setResourceDisplayName(name: string): AuthorizationException; + throwException(): void; + } + + /** + * A base class for all buttons. + */ + export interface Button { + setAuthorizationAction(action: AuthorizationAction): Button; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): Button; + setOnClickAction(action: Action): Button; + setOnClickOpenLinkAction(action: Action): Button; + setOpenLink(openLink: OpenLink): Button; + } + + /** + * Holds a set of Button objects that are displayed in a row. + * + * var textButton = CardService.newTextButton(); + * // Finish building the text button... + * + * var imageButton = CardService.newImageButton(); + * // Finish building the image button... + * + * var buttonSet = CardService.newButtonSet() + * .addButton(textButton) + * .addButton(imageButton); + */ + export interface ButtonSet { + addButton(button: Button): ButtonSet; + } + + /** + * A context card that represents a single view in the + * UI. + * + * var cardSection = CardService.newCardSection(); + * // Finish building the card section ... + * + * var card = CardService.newCardBuilder() + * .setName("Card name") + * .setHeader(CardService.newCardHeader().setTitle("Card title")) + * .addSection(cardSection) + * .build(); + */ + export interface Card { + printJson(): string; + } + + /** + * A clickable menu item that is added to the card header menu. + * + * var action = CardService.newAction(); + * // Finish building the action... + * + * var cardAction = CardService.newCardAction() + * .setText("Card action") + * .setOnClickAction(action); + */ + export interface CardAction { + setAuthorizationAction(action: AuthorizationAction): CardAction; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): CardAction; + setOnClickAction(action: Action): CardAction; + setOnClickOpenLinkAction(action: Action): CardAction; + setOpenLink(openLink: OpenLink): CardAction; + setText(text: string): CardAction; + } + + /** + * A builder for Card objects. + */ + export interface CardBuilder { + addCardAction(cardAction: CardAction): CardBuilder; + addSection(section: CardSection): CardBuilder; + build(): Card; + setHeader(cardHeader: CardHeader): CardBuilder; + setName(name: string): CardBuilder; + } + + /** + * The header of a Card. + * + * var cardHeader = CardService.newCardHeader() + * .setTitle("Card header title") + * .setSubtitle("Card header subtitle") + * .setImageStyle(CardService.ImageStyle.CIRCLE) + * .setImageUrl("https://image.png"); + */ + export interface CardHeader { + setImageAltText(imageAltText: string): CardHeader; + setImageStyle(imageStyle: ImageStyle): CardHeader; + setImageUrl(imageUrl: string): CardHeader; + setSubtitle(subtitle: string): CardHeader; + setTitle(title: string): CardHeader; + } + + /** + * A card section holds groups of widgets and provides visual separation between them. + * + * var image = CardService.newImage(); + * // Build image ... + * var textParagraph = CardService.newTextParagraph(); + * // Build text paragraph ... + * + * var cardSection = CardService.newCardSection() + * .setHeader("Section header") + * .addWidget(image) + * .addWidget(textParagraph); + */ + export interface CardSection { + addWidget(widget: Widget): CardSection; + setCollapsible(collapsible: boolean): CardSection; + setHeader(header: string): CardSection; + setNumUncollapsibleWidgets(numUncollapsibleWidgets: Integer): CardSection; + } + + /** + * CardService provides the ability to create generic cards used across different Google + * extensibility products, such as Gmail add-ons. + * + * Currently you can only use this service to construct Gmail add-ons. + * + * return CardService.newCardBuilder() + * .setHeader(CardService.newCardHeader().setTitle("CardTitle")) + * .build(); + * + * Or you can return multiple Cards like so: + * + * return [ + * CardService.newCardBuilder().build(), + * CardService.newCardBuilder().build(), + * CardService.newCardBuilder().build() + * ] + * + * The following shows how you could define a card with a header, text, an image and a menu item: + * + * function createWidgetDemoCard() { + * return CardService + * .newCardBuilder() + * .setHeader( + * CardService.newCardHeader() + * .setTitle('Widget demonstration') + * .setSubtitle('Check out these widgets') + * .setImageStyle(CardService.ImageStyle.SQUARE) + * .setImageUrl( + * 'https://www.example.com/images/headerImage.png')) + * .addSection( + * CardService.newCardSection() + * .setHeader('Simple widgets') // optional + * .addWidget(CardService.newTextParagraph().setText( + * 'These widgets are display-only. ' + + * 'A text paragraph can have multiple lines and ' + + * 'formatting.')) + * .addWidget(CardService.newImage().setImageUrl( + * 'https://www.example.com/images/mapsImage.png'))) + * .addCardAction(CardService.newCardAction().setText('Gmail').setOpenLink( + * CardService.newOpenLink().setUrl('https://mail.google.com/mail'))) + * .build(); + * } + */ + export interface CardService { + ComposedEmailType: typeof ComposedEmailType; + ContentType: typeof ContentType; + Icon: typeof Icon; + ImageStyle: typeof ImageStyle; + LoadIndicator: typeof LoadIndicator; + NotificationType: typeof NotificationType; + OnClose: typeof OnClose; + OpenAs: typeof OpenAs; + SelectionInputType: typeof SelectionInputType; + TextButtonStyle: typeof TextButtonStyle; + UpdateDraftBodyType: typeof UpdateDraftBodyType; + newAction(): Action; + newActionResponseBuilder(): ActionResponseBuilder; + newAuthorizationAction(): AuthorizationAction; + newAuthorizationException(): AuthorizationException; + newButtonSet(): ButtonSet; + newCardAction(): CardAction; + newCardBuilder(): CardBuilder; + newCardHeader(): CardHeader; + newCardSection(): CardSection; + newComposeActionResponseBuilder(): ComposeActionResponseBuilder; + newImage(): Image; + newImageButton(): ImageButton; + newKeyValue(): KeyValue; + newNavigation(): Navigation; + newNotification(): Notification; + newOpenLink(): OpenLink; + newSelectionInput(): SelectionInput; + newSuggestions(): Suggestions; + newSuggestionsResponseBuilder(): SuggestionsResponseBuilder; + newSwitch(): Switch; + newTextButton(): TextButton; + newTextInput(): TextInput; + newTextParagraph(): TextParagraph; + newUniversalActionResponseBuilder(): UniversalActionResponseBuilder; + newUpdateDraftActionResponseBuilder(): UpdateDraftActionResponseBuilder; + newUpdateDraftBodyAction(): UpdateDraftBodyAction; + } + + /** + * The response object that may be returned from a callback method for compose action in a Gmail add-on. + * + * Note: This object isn't related to compose actions that are + * used to extend the compose UI. Rather, + * this object is a response to an Action that composes draft messages when a specific UI element is + * selected. + * + * var composeActionResponse = CardService.newComposeActionResponseBuilder() + * .setGmailDraft(GmailApp.createDraft("recipient", "subject", "body")) + * .build(); + */ + export interface ComposeActionResponse { + printJson(): string; + } + + /** + * A builder for ComposeActionResponse objects. + * + * Note: This object isn't related to compose actions that are + * used to extend the compose UI. Rather, + * this builder creates responses to an Action that composes draft messages when a specific + * UI element is selected. + */ + export interface ComposeActionResponseBuilder { + build(): ComposeActionResponse; + setGmailDraft(draft: Gmail.GmailDraft): ComposeActionResponseBuilder; + } + + /** + * An enum value that specifies whether the composed email is a standalone or reply draft. + */ + export enum ComposedEmailType { REPLY_AS_DRAFT, STANDALONE_DRAFT } + + /** + * An enum value that specifies the content type of the content generated by a UpdateDraftActionResponse. + */ + export enum ContentType { TEXT, MUTABLE_HTML, IMMUTABLE_HTML } + + /** + * Predefined icons that can be used in various UI objects, such as ImageButton or KeyValue widgets. + */ + export enum Icon { NONE, AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DOLLAR, DESCRIPTION, EMAIL, EVENT_PERFORMER, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, OFFER, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } + + /** + * A widget that shows a single image. + * + * var image = CardService.newImage().setAltText("A nice image").setImageUrl("https://image.png"); + */ + export interface Image { + setAltText(altText: string): Image; + setAuthorizationAction(action: AuthorizationAction): Image; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): Image; + setImageUrl(url: string): Image; + setOnClickAction(action: Action): Image; + setOnClickOpenLinkAction(action: Action): Image; + setOpenLink(openLink: OpenLink): Image; + } + + /** + * A ImageButton with an image displayed on it. + * + * var imageButton = CardService.newImageButton() + * .setAltText("An image button with an airplane icon.") + * .setIcon(CardService.Icon.AIRPLANE) + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://airplane.com")); + */ + export interface ImageButton { + setAltText(altText: string): ImageButton; + setAuthorizationAction(action: AuthorizationAction): ImageButton; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): ImageButton; + setIcon(icon: Icon): ImageButton; + setIconUrl(url: string): ImageButton; + setOnClickAction(action: Action): ImageButton; + setOnClickOpenLinkAction(action: Action): ImageButton; + setOpenLink(openLink: OpenLink): ImageButton; + } + + /** + * An enum that defines an image cropping style. + */ + export enum ImageStyle { SQUARE, CIRCLE } + + /** + * A widget that displays one or more "keys" around a text "value". The possible keys include an + * icon, a label above and a label below. Setting the text content and one of the keys is required + * using setContent(text) and one of setIcon(icon), setIconUrl(url), setTopLabel(text), + * or setBottomLabel(text). + * + * var imageKeyValue = CardService.newKeyValue() + * .setIconUrl("https://icon.png") + * .setContent("KeyValue widget with an image on the left and text on the right"); + * + * var textKeyValue = CardService.newKeyValue() + * .setTopLabel("Text key") + * .setContent("KeyValue widget with text key on top and cotent below"); + * + * var multilineKeyValue = CardService.newKeyValue() + * .setTopLabel("Top label - single line)") + * .setContent("Content can be multiple lines") + * .setMultiline(true) + * .setBottomLabel("Bottom label - single line"); + */ + export interface KeyValue { + setAuthorizationAction(action: AuthorizationAction): KeyValue; + setBottomLabel(text: string): KeyValue; + setButton(button: Button): KeyValue; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): KeyValue; + setContent(text: string): KeyValue; + setIcon(icon: Icon): KeyValue; + setIconAltText(altText: string): KeyValue; + setIconUrl(url: string): KeyValue; + setMultiline(multiline: boolean): KeyValue; + setOnClickAction(action: Action): KeyValue; + setOnClickOpenLinkAction(action: Action): KeyValue; + setOpenLink(openLink: OpenLink): KeyValue; + setSwitch(switchToSet: Switch): KeyValue; + setTopLabel(text: string): KeyValue; + } + + /** + * An enum type that specifies the type of loading or progress indicator to display while an Action is being processed. + */ + export enum LoadIndicator { SPINNER, NONE } + + /** + * A helper object that controls card navigation. See the card navigation guide for more details. + */ + export interface Navigation { + popCard(): Navigation; + popToNamedCard(cardName: string): Navigation; + popToRoot(): Navigation; + printJson(): string; + pushCard(card: Card): Navigation; + updateCard(card: Card): Navigation; + } + + /** + * A notification shown to the user as a response to interacting with a UI element. + * + * var action = CardService.newAction().setFunctionName("notificationCallback"); + * CardService.newTextButton().setText('Save').setOnClickAction(action); + * + * // ... + * + * function notificationCallback() { + * return CardService.newActionResponseBuilder() + * .setNotification(CardService.newNotification() + * .setType(CardService.NotificationType.WARNING) + * .setText("Some info to display to user")) + * .build(); + * } + */ + export interface Notification { + setText(text: string): Notification; + setType(type: NotificationType): Notification; + } + + /** + * Type of notification to show. + */ + export enum NotificationType { INFO, ERROR, WARNING } + + /** + * An enum that specifies what to do when a URL opened through an OpenLink is closed. + * + * When a link is opened, the client either forgets about it or waits until the window is closed. + * The implementation depends on the client platform capabilities. OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, + * OnClose takes precedence. + */ + export enum OnClose { NOTHING, RELOAD_ADD_ON } + + /** + * An enum that specifies how to open a URL. + * + * The client can open a URL as either a full size window (if that is the frame used by the + * client), or an overlay (such as a pop-up). The implementation depends on the client platform + * capabilities, and the value selected may be ignored if the client does not support it. FULL_SIZE is supported by all clients. + * + * Using OnClose may cause OpenAs to be ignored; if the client platform cannot + * support both selected values together, OnClose takes precedence. + */ + export enum OpenAs { FULL_SIZE, OVERLAY } + + /** + * Represents an action to open a link with some options. + * + * // A button that opens as a link in an overlay and + * // requires a reload when closed. + * var button = CardService.newTextButton() + * .setText("This button opens a link in an overlay window") + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://www.google.com") + * .setOpenAs(CardService.OpenAs.OVERLAY) + * .setOnClose(CardService.OnClose.RELOAD_ADD_ON)); + * + * // An action response that opens a link in full screen and + * // requires no action when closed. + * var actionResponse = CardService.newActionResponseBuilder() + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://www.google.com") + * .setOpenAs(CardService.OpenAs.FULL_SIZE) + * .setOnClose(CardService.OnClose.NOTHING)); + * .build(); + */ + export interface OpenLink { + setOnClose(onClose: OnClose): OpenLink; + setOpenAs(openAs: OpenAs): OpenLink; + setUrl(url: string): OpenLink; + } + + /** + * An input field that allows choosing between a set of predefined options. + * + * var checkboxGroup = CardService.newSelectionInput() + * .setType(CardService.SelectionInputType.CHECK_BOX) + * .setTitle("A group of checkboxes. Multiple selections are allowed.") + * .setFieldName("checkbox_field") + * .addItem("checkbox one title", "checkbox_one_value", false) + * .addItem("checkbox two title", "checkbox_two_value", true) + * .addItem("checkbox three title", "checkbox_three_value", false) + * .setOnChangeAction(CardService.newAction() + * .setFunctionName("handleCheckboxChange")); + * + * var radioGroup = CardService.newSelectionInput() + * .setType(CardService.SelectionInputType.RADIO_BUTTON) + * .setTitle("A group of radio buttons. Only a single selection is allowed.") + * .setFieldName("checkbox_field") + * .addItem("radio button one title", "radio_one_value", true) + * .addItem("radio button two title", "radio_two_value", true) + * .addItem("radio button three title", "radio_three_value", false); + */ + export interface SelectionInput { + addItem(text: Object, value: Object, selected: boolean): SelectionInput; + setFieldName(fieldName: string): SelectionInput; + setOnChangeAction(action: Action): SelectionInput; + setTitle(title: string): SelectionInput; + setType(type: SelectionInputType): SelectionInput; + } + + /** + * Type of selection input. + */ + export enum SelectionInputType { CHECK_BOX, RADIO_BUTTON, DROPDOWN } + + /** + * Autocomplete suggestions to supplement a TextInput widget. + * + * var textInput = CardService.newTextInput() + * .setSuggestions(CardService.newSuggestions() + * .addSuggestion("First suggestion") + * .addSuggestion("Second suggestion")) + */ + export interface Suggestions { + addSuggestion(suggestion: string): Suggestions; + addSuggestions(suggestions: Object[]): Suggestions; + } + + /** + * A response object that can be returned from a suggestions callback function. This is used with + * TextInput widgets that implement autocomplete. + * + * var suggestionsResponse = CardService.newSuggestionsResponseBuilder() + * .setSuggestions(CardService.newSuggestions() + * .addSuggestion("First suggestion") + * .addSuggestion("Second suggestion")) + * .build(); + */ + export interface SuggestionsResponse { + printJson(): string; + } + + /** + * A builder for SuggestionsResponse objects. + */ + export interface SuggestionsResponseBuilder { + build(): SuggestionsResponse; + setSuggestions(suggestions: Suggestions): SuggestionsResponseBuilder; + } + + /** + * A UI element that supports being toggled on or off. This can only be used within a KeyValue widget. + * + * var switchKeyValue = CardService.newKeyValue() + * .setTopLabel("Switch key value widget label") + * .setContent("This is a key value widget with a switch on the right") + * .setSwitch(CardService.newSwitch() + * .setFieldName("form_input_switch_key") + * .setValue("form_input_switch_value") + * .setOnChangeAction(CardService.newAction() + * .setFunctionName("handleSwitchChange"))); + */ + export interface Switch { + setFieldName(fieldName: string): Switch; + setOnChangeAction(action: Action): Switch; + setSelected(selected: boolean): Switch; + setValue(value: string): Switch; + } + + /** + * A TextButton with a text label. + * + * var textButton = CardService.newTextButton() + * .setText("Open Link") + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://www.google.com")); + */ + export interface TextButton { + setAuthorizationAction(action: AuthorizationAction): TextButton; + setBackgroundColor(backgroundColor: string): TextButton; + setComposeAction(action: Action, composedEmailType: ComposedEmailType): TextButton; + setDisabled(disabled: boolean): TextButton; + setOnClickAction(action: Action): TextButton; + setOnClickOpenLinkAction(action: Action): TextButton; + setOpenLink(openLink: OpenLink): TextButton; + setText(text: string): TextButton; + setTextButtonStyle(textButtonStyle: TextButtonStyle): TextButton; + } + + /** + * An enum that specifies the style for TextButton. + * + * TEXT is the default; it renders a simple text button with clear background. + * FILLED buttons have a background color you can set with + * TextButton.setBackgroundColor(backgroundColor). + */ + export enum TextButtonStyle { TEXT, FILLED } + + /** + * A input field widget that accepts text input. + * + * var textInput = CardService.newTextInput() + * .setFieldName("text_input_form_input_key") + * .setTitle("Text input title") + * .setHint("Text input hint"); + */ + export interface TextInput { + setFieldName(fieldName: string): TextInput; + setHint(hint: string): TextInput; + setMultiline(multiline: boolean): TextInput; + setOnChangeAction(action: Action): TextInput; + setSuggestions(suggestions: Suggestions): TextInput; + setSuggestionsAction(suggestionsAction: Action): TextInput; + setTitle(title: string): TextInput; + setValue(value: string): TextInput; + } + + /** + * A widget that displays text and supports basic HTML formatting. + * + * var textParagraph = CardService.newTextParagraph() + * .setText("This is a text paragraph widget. Multiple lines are allowed if needed."); + */ + export interface TextParagraph { + setText(text: string): TextParagraph; + } + + /** + * The response object that may be returned from a method that creates universal action. + * + * // A universal action that opens a link. + * var openLinkUniversalAction = CardService.newUniversalActionResponseBuilder() + * .setOpenLink(CardService.newOpenLink() + * .setUrl("https://www.google.com")) + * .build(); + * + * var cardBuilder1 = CardService.newCardBuilder(); + * var cardBuilder2 = CardService.newCardBuilder(); + * // Finish building the cards ... + * + * // A universal action that shows two static cards. + * var cardsUniversalAction = CardService.newUniversalActionResponseBuilder() + * .displayAddOnCards([ + * cardBuilder1.build(); + * cardBuilder2.build(); + * ]).build(); + */ + export interface UniversalActionResponse { + printJson(): string; + } + + /** + * A builder for the UniversalActionResponse objects. + */ + export interface UniversalActionResponseBuilder { + build(): UniversalActionResponse; + displayAddOnCards(cardObjects: Object[]): UniversalActionResponseBuilder; + setOpenLink(openLink: OpenLink): UniversalActionResponseBuilder; + } + + /** + * Represents an action that updates the email draft that the user is currently editing. + * + * // A UpdateDraftActionResponse that inserts non-editable content (a link in this case) into an + * // email draft. + * var updateDraftActionResponse = CardService.newUpdateDraftActionResponseBuilder() + * .setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction() + * .addUpdateContent( + * "Google", + * ContentType.IMMUTABLE_HTML) + * .setUpdateType(UpdateDraftBodyType.IN_PLACE_INSERT)) + * .build(); + * + * // A UpdateDraftActionResponse that inserts a link into an email draft. The added content can be + * // edited further. + * var updateDraftActionResponse = CardService.newUpdateDraftActionResponseBuilder() + * .setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction() + * .addUpdateContent( + * "Google", + * ContentType.MUTABLE_HTML) + * .setUpdateType(UpdateDraftBodyType.IN_PLACE_INSERT)) + * .build(); + * + * // A UpdateDraftActionResponse that inserts multiple values of different types. + * // The example action response inserts two lines next to each other in the email + * // draft, at the cursor position. Each line contains the content added by + * // {@link UpdateDraftActionResponseBuilder#addUpdateContent}. + * var updateDraftActionResponse = CardService.newUpdateDraftActionResponseBuilder() + * .setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction() + * .addUpdateContent( + * "Google", + * ContentType.MUTABLE_HTML) + * .addUpdateContent("Above is a google link.", ContentType.PLAIN_TEXT) + * .setUpdateType(UpdateDraftBodyType.IN_PLACE_INSERT)) + * .build(); + */ + export interface UpdateDraftActionResponse { + printJson(): string; + } + + /** + * A builder for UpdateDraftActionResponse objects. + */ + export interface UpdateDraftActionResponseBuilder { + build(): UpdateDraftActionResponse; + setUpdateDraftBodyAction(updateDraftBodyAction: UpdateDraftBodyAction): UpdateDraftActionResponseBuilder; + } + + /** + * Represents an action that updates the email draft body. + */ + export interface UpdateDraftBodyAction { + addUpdateContent(content: string, contentType: ContentType): UpdateDraftBodyAction; + setUpdateType(updateType: UpdateDraftBodyType): UpdateDraftBodyAction; + } + + /** + * An enum value that specifies the type of an UpdateDraftBodyAction. + */ + export enum UpdateDraftBodyType { IN_PLACE_INSERT } + + /** + * Base class for all widgets that can be added to a Card. + */ + export interface Widget { + } + + } +} + +declare var CardService: GoogleAppsScript.Card_Service.CardService; diff --git a/types/google-apps-script/google-apps-script.charts.d.ts b/types/google-apps-script/google-apps-script.charts.d.ts index 50013a36d0..5898092bb4 100644 --- a/types/google-apps-script/google-apps-script.charts.d.ts +++ b/types/google-apps-script/google-apps-script.charts.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -536,7 +536,7 @@ declare namespace GoogleAppsScript { * function doGet() { * // This example creates two table charts side by side. One uses a data view definition to * // restrict the number of displayed columns. - * var app = UiApp.createApplication(); + * * // Get sample data from a spreadsheet. * var dataSourceUrl = 'https://docs.google.com/spreadsheet/tq?range=A1%3AF' + * '&key=0Aq4s9w_HxMs7dHpfX05JdmVSb1FpT21sbXd4NVE3UEE&gid=4&headers=-1'; @@ -555,9 +555,17 @@ declare namespace GoogleAppsScript { * .setDataViewDefinition(dataViewDefinition) * .build(); * - * var panel = app.createHorizontalPanel().setSpacing(15); - * panel.add(originalChart).add(limitedChart); - * return app.add(panel); + * var htmlOutput = HtmlService.createHtmlOutput(); + * var originalChartData = Utilities.base64Encode(originalChart.getAs('image/png').getBytes()); + * var originalChartUrl = "data:image/png;base64," + encodeURI(originalChartData); + * var limitedChartData = Utilities.base64Encode(limitedChart.getAs('image/png').getBytes()); + * var limitedChartUrl = "data:image/png;base64," + encodeURI(limitedChartData); + * htmlOutput.append("
"); + * htmlOutput.append(""); + * htmlOutput.append(""); + * htmlOutput.append(""); + * htmlOutput.append("
"); + * return htmlOutput; * } */ export interface DataViewDefinitionBuilder { diff --git a/types/google-apps-script/google-apps-script.data-studio.d.ts b/types/google-apps-script/google-apps-script.data-studio.d.ts new file mode 100644 index 0000000000..572e4284e1 --- /dev/null +++ b/types/google-apps-script/google-apps-script.data-studio.d.ts @@ -0,0 +1,301 @@ +// Type definitions for Google Apps Script 2018-12-26 +// Project: https://developers.google.com/apps-script/ +// Definitions by: motemen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace GoogleAppsScript { + export module Data_Studio { + /** + * An enum that defines the aggregation types that can be set for a Field. + */ + export enum AggregationType { NO_AGGREGATION, AVG, COUNT, COUNT_DISTINCT, MAX, MIN, SUM } + + /** + * Contains checkbox information for the config. Its properties determine how the checkbox is + * displayed in Data Studio. + * + * var checkbox = config.newCheckbox() + * .setId("use_https") + * .setName("Use Https?") + * .setHelpText("Whether or not https should be used.") + * .setAllowOverride(true); + */ + export interface Checkbox { + setAllowOverride(allowOverride: boolean): Checkbox; + setHelpText(helpText: string): Checkbox; + setId(id: string): Checkbox; + setName(name: string): Checkbox; + } + + /** + * CommunityConnector enables scripts to access builders and utilities to help with development of + * Community Connectors for Data Studio. Use this class to get a reference to the Fields + * object and the FieldType and AggregationType enums so they can be used in the + * construction of Fields. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var fieldType = cc.FieldType; + * var aggregationType = cc.AggregationType; + * + * var fields = cc.getFields(); + * + * fields.newMetric() + * .setAggregation(aggregationType.AVG) + * .setFieldType(fieldType.CURRENCY_USD); + */ + export interface CommunityConnector { + AggregationType: typeof AggregationType; + FieldType: typeof FieldType; + getConfig(): Config; + getFields(): Fields; + } + + /** + * Contains the configuration entries for a connector. These configuration entries define what + * questions are asked when adding a new connector. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var config = cc.getConfig(); + * + * var info_entry = config.newInfo() + * .setId("info_id") + * .setHelpText("This connector can connect to multiple data endpoints."); + */ + export interface Config { + build(): Object; + newCheckbox(): Checkbox; + newInfo(): Info; + newOptionBuilder(): OptionBuilder; + newSelectMultiple(): SelectMultiple; + newSelectSingle(): SelectSingle; + newTextArea(): TextArea; + newTextInput(): TextInput; + printJson(): string; + setDateRangeRequired(dateRangeRequired: boolean): Config; + } + + /** + * DataStudioApp allows scripts to interact with developer-oriented features for Data Studio. + */ + export interface DataStudioApp { + createCommunityConnector(): CommunityConnector; + } + + /** + * Contains field-related data. Its properties determine how the field is used in Data Studio. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var fields = cc.getFields(); + * var types = cc.FieldType; + * + * var field1 = fields.newDimension() + * .setId('field1_id') + * .setName('Field 1 ID') + * .setDescription('The first field.') + * .setType(types.YEAR_MONTH) + * .setGroup('DATETIME'); + */ + export interface Field { + getAggregation(): AggregationType; + getDescription(): string; + getFormula(): string; + getGroup(): string; + getId(): string; + getName(): string; + getType(): FieldType; + isDefault(): boolean; + isDimension(): boolean; + isHidden(): boolean; + isMetric(): boolean; + setAggregation(aggregation: AggregationType): Field; + setDescription(description: string): Field; + setFormula(formula: string): Field; + setGroup(group: string): Field; + setId(id: string): Field; + setIsHidden(isHidden: boolean): Field; + setName(name: string): Field; + setType(type: FieldType): Field; + } + + /** + * An enum that defines the types that can be set for a Field. + */ + export enum FieldType { YEAR, YEAR_QUARTER, YEAR_MONTH, YEAR_WEEK, YEAR_MONTH_DAY, YEAR_MONTH_DAY_HOUR, QUARTER, MONTH, WEEK, MONTH_DAY, DAY_OF_WEEK, DAY, HOUR, MINUTE, DURATION, COUNTRY, COUNTRY_CODE, CONTINENT, CONTINENT_CODE, SUB_CONTINENT, SUB_CONTINENT_CODE, REGION, REGION_CODE, CITY, CITY_CODE, METRO, METRO_CODE, LATITUDE_LONGITUDE, NUMBER, PERCENT, TEXT, BOOLEAN, URL, CURRENCY_AED, CURRENCY_ALL, CURRENCY_ARS, CURRENCY_AUD, CURRENCY_BDT, CURRENCY_BGN, CURRENCY_BOB, CURRENCY_BRL, CURRENCY_CAD, CURRENCY_CDF, CURRENCY_CHF, CURRENCY_CLP, CURRENCY_CNY, CURRENCY_COP, CURRENCY_CRC, CURRENCY_CZK, CURRENCY_DKK, CURRENCY_DOP, CURRENCY_EGP, CURRENCY_ETB, CURRENCY_EUR, CURRENCY_GBP, CURRENCY_HKD, CURRENCY_HRK, CURRENCY_HUF, CURRENCY_IDR, CURRENCY_ILS, CURRENCY_INR, CURRENCY_IRR, CURRENCY_ISK, CURRENCY_JMD, CURRENCY_JPY, CURRENCY_KRW, CURRENCY_LKR, CURRENCY_LTL, CURRENCY_MNT, CURRENCY_MVR, CURRENCY_MXN, CURRENCY_MYR, CURRENCY_NOK, CURRENCY_NZD, CURRENCY_PAB, CURRENCY_PEN, CURRENCY_PHP, CURRENCY_PKR, CURRENCY_PLN, CURRENCY_RON, CURRENCY_RSD, CURRENCY_RUB, CURRENCY_SAR, CURRENCY_SEK, CURRENCY_SGD, CURRENCY_THB, CURRENCY_TRY, CURRENCY_TWD, CURRENCY_TZS, CURRENCY_UAH, CURRENCY_USD, CURRENCY_UYU, CURRENCY_VEF, CURRENCY_VND, CURRENCY_YER, CURRENCY_ZAR } + + /** + * Contains a set of Fields for a community connector. This set of fields define which + * dimensions and metrics can be used in Data Studio. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var fields = cc.getFields(); + * var types = cc.FieldType; + * + * var field1 = fields.newDimension() + * // Set other properties as needed. + * .setId('field1_id'); + */ + export interface Fields { + asArray(): Field[]; + build(): Object[]; + forIds(ids: string[]): Fields; + getDefaultDimension(): Field; + getDefaultMetric(): Field; + getFieldById(fieldId: string): Field; + newDimension(): Field; + newMetric(): Field; + setDefaultDimension(fieldId: string): void; + setDefaultMetric(fieldId: string): void; + } + + /** + * Contains info data for the config. Its properties determine how the info is displayed in Data + * Studio. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var config = cc.getConfig(); + * + * var info1 = config.newInfo() + * .setName("info1") + * .setText("This text gives some context on the configuration."); + */ + export interface Info { + setId(id: string): Info; + setText(text: string): Info; + } + + /** + * A builder for creating options for SelectSingles and SelectMultiples. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var config = cc.getConfig(); + * + * var option1 = config.newOptionBuilder() + * .setLabel("option label") + * .setValue("option_value"); + * + * var option2 = config.newOptionBuilder() + * .setLabel("second option label") + * .setValue("option_value_2"); + * + * var info1 = config.newSelectSingle() + * .setId("api_endpoint") + * .setName("Data Type") + * .setHelpText("Select the data type you're interested in.") + * .addOption(option1) + * .addOption(option2); + */ + export interface OptionBuilder { + setLabel(label: string): OptionBuilder; + setValue(value: string): OptionBuilder; + } + + /** + * Contains select multiple information for the config. Its properties determine how the select + * multiple is displayed in Data Studio. + * + * Usage: + * + * var option1 = config.newOptionBuilder() + * .setLabel("option label") + * .setValue("option_value"); + * + * var option2 = config.newOptionBuilder() + * .setLabel("second option label") + * .setValue("option_value_2"); + * + * var info1 = config.newSelectMultiple() + * .setId("api_endpoint") + * .setName("Data Type") + * .setHelpText("Select the data type you're interested in.") + * .setAllowOverride(true) + * .addOption(option1) + * .addOption(option2); + */ + export interface SelectMultiple { + addOption(optionBuilder: OptionBuilder): SelectMultiple; + setAllowOverride(allowOverride: boolean): SelectMultiple; + setHelpText(helpText: string): SelectMultiple; + setId(id: string): SelectMultiple; + setName(name: string): SelectMultiple; + } + + /** + * Contains select single information for the config. Its properties determine how the select single + * is displayed in Data Studio. + * + * var option1 = config.newOptionBuilder() + * .setLabel("option label") + * .setValue("option_value"); + * + * var option2 = config.newOptionBuilder() + * .setLabel("second option label") + * .setValue("option_value_2"); + * + * var info1 = config.newSelectMultiple() + * .setId("api_endpoint") + * .setName("Data Type") + * .setHelpText("Select the data type you're interested in.") + * .setAllowOverride(true) + * .addOption(option1) + * .addOption(option2); + */ + export interface SelectSingle { + addOption(optionBuilder: OptionBuilder): SelectSingle; + setAllowOverride(allowOverride: boolean): SelectSingle; + setHelpText(helpText: string): SelectSingle; + setId(id: string): SelectSingle; + setName(name: string): SelectSingle; + } + + /** + * Contains text area information for the config. Its properties determine how the text input is + * displayed in Data Studio. + * + * Usage: + * + * var cc = DataStudioApp.createCommunityConnector(); + * var config = cc.getConfig(); + * + * var textArea1 = config.newTextArea() + * .setId("textArea1") + * .setName("Search") + * .setHelpText("for example, Coldplay") + * .setAllowOverride(true) + * .setPlaceholder("Search for an artist for all songs."); + */ + export interface TextArea { + setAllowOverride(allowOverride: boolean): TextArea; + setHelpText(helpText: string): TextArea; + setId(id: string): TextArea; + setName(name: string): TextArea; + setPlaceholder(placeholder: string): TextArea; + } + + /** + * Contains text input information for the config. Its properties determine how the text input is + * displayed in Data Studio. + * + * var cc = DataStudioApp.createCommunityConnector(); + * var config = cc.getConfig(); + * + * var info1 = config.newTextInput() + * .setId("info1") + * .setName("Search") + * .setHelpText("for example, Coldplay") + * .setAllowOverride(true) + * .setPlaceholder("Search for an artist for all songs."); + */ + export interface TextInput { + setAllowOverride(allowOverride: boolean): TextInput; + setHelpText(helpText: string): TextInput; + setId(id: string): TextInput; + setName(name: string): TextInput; + setPlaceholder(placeholder: string): TextInput; + } + + } +} + +declare var DataStudioApp: GoogleAppsScript.Data_Studio.DataStudioApp; diff --git a/types/google-apps-script/google-apps-script.forms.d.ts b/types/google-apps-script/google-apps-script.forms.d.ts index df08002505..33df1975c7 100644 --- a/types/google-apps-script/google-apps-script.forms.d.ts +++ b/types/google-apps-script/google-apps-script.forms.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -151,9 +151,6 @@ declare namespace GoogleAppsScript { * checkBoxItem.setValidation(checkBoxValidation); */ export interface CheckboxValidation { - requireSelectAtLeast(number: Integer): CheckboxValidation; - requireSelectAtMost(number: Integer): CheckboxValidation; - requireSelectExactly(number: Integer): CheckboxValidation; } /** @@ -671,7 +668,7 @@ declare namespace GoogleAppsScript { * item.setHelpText('Description of new section.'); * } */ - export enum ItemType { CHECKBOX, CHECKBOX_GRID, DATE, DATETIME, DURATION, GRID, IMAGE, LIST, MULTIPLE_CHOICE, PAGE_BREAK, PARAGRAPH_TEXT, SCALE, SECTION_HEADER, TEXT, TIME } + export enum ItemType { CHECKBOX, CHECKBOX_GRID, DATE, DATETIME, DURATION, GRID, IMAGE, LIST, MULTIPLE_CHOICE, PAGE_BREAK, PARAGRAPH_TEXT, SCALE, SECTION_HEADER, TEXT, TIME, VIDEO } /** * A question item that allows the respondent to select one choice from a drop-down list. Items can diff --git a/types/google-apps-script/google-apps-script.gmail.d.ts b/types/google-apps-script/google-apps-script.gmail.d.ts index db8e6ecc52..b71a7226b6 100644 --- a/types/google-apps-script/google-apps-script.gmail.d.ts +++ b/types/google-apps-script/google-apps-script.gmail.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -103,6 +103,7 @@ declare namespace GoogleAppsScript { getContentType(): string; getDataAsString(): string; getDataAsString(charset: string): string; + getHash(): string; getName(): string; getSize(): Integer; isGoogleType(): boolean; diff --git a/types/google-apps-script/google-apps-script.groups.d.ts b/types/google-apps-script/google-apps-script.groups.d.ts index 757029f044..958838de57 100644 --- a/types/google-apps-script/google-apps-script.groups.d.ts +++ b/types/google-apps-script/google-apps-script.groups.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,13 +16,13 @@ declare namespace GoogleAppsScript { * * function listGroupMembers() { * var group = GroupsApp.getGroupByEmail("example@googlegroups.com"); - * var s = group.getEmail() + ': '; + * var str = group.getEmail() + ': '; * var users = group.getUsers(); * for (var i = 0; i < users.length; i++) { * var user = users[i]; - * s = s + user.getEmail() + ", "; + * str = str + user.getEmail() + ", "; * } - * Logger.log(s); + * Logger.log(str); * } */ export interface Group { diff --git a/types/google-apps-script/google-apps-script.script.d.ts b/types/google-apps-script/google-apps-script.script.d.ts index fbe95deb8c..5130b54db9 100644 --- a/types/google-apps-script/google-apps-script.script.d.ts +++ b/types/google-apps-script/google-apps-script.script.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,8 +15,8 @@ declare namespace GoogleAppsScript { * An enumeration that identifies which categories of authorized services Apps Script is able to * execute through a triggered function. These values are exposed in triggered functions as the authMode * property of the event parameter, e. For - * more information, see the guide to the authorization - * lifecycle for add-ons. + * more information, see the guide to the + * authorization lifecycle for add-ons. * * function onOpen(e) { * var menu = SpreadsheetApp.getUi().createAddonMenu(); diff --git a/types/google-apps-script/google-apps-script.slides.d.ts b/types/google-apps-script/google-apps-script.slides.d.ts index 3d1aac9227..f1c3a6fdae 100644 --- a/types/google-apps-script/google-apps-script.slides.d.ts +++ b/types/google-apps-script/google-apps-script.slides.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -125,6 +125,14 @@ declare namespace GoogleAppsScript { */ export enum ColorType { UNSUPPORTED, RGB, THEME } + /** + * The connection site on a PageElement that can connect to a connector. + */ + export interface ConnectionSite { + getIndex(): Integer; + getPageElement(): PageElement; + } + /** * The content alignments for a Shape or TableCell. The supported alignments * correspond to predefined text anchoring types from the ECMA-376 standard. @@ -172,8 +180,11 @@ declare namespace GoogleAppsScript { */ export interface Group { alignOnPage(alignmentPosition: AlignmentPosition): Group; + bringForward(): Group; + bringToFront(): Group; duplicate(): PageElement; getChildren(): PageElement[]; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getHeight(): Number; getInherentHeight(): Number; @@ -194,9 +205,13 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): Group; select(): void; select(replace: boolean): void; + sendBackward(): Group; + sendToBack(): Group; + setDescription(description: string): Group; setHeight(height: Number): Group; setLeft(left: Number): Group; setRotation(angle: Number): Group; + setTitle(title: string): Group; setTop(top: Number): Group; setTransform(transform: AffineTransform): Group; setWidth(width: Number): Group; @@ -208,10 +223,13 @@ declare namespace GoogleAppsScript { */ export interface Image { alignOnPage(alignmentPosition: AlignmentPosition): Image; + bringForward(): Image; + bringToFront(): Image; duplicate(): PageElement; getAs(contentType: string): Base.Blob; getBlob(): Base.Blob; getBorder(): Border; + getConnectionSites(): ConnectionSite[]; getContentUrl(): string; getDescription(): string; getHeight(): Number; @@ -240,6 +258,9 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): Image; select(): void; select(replace: boolean): void; + sendBackward(): Image; + sendToBack(): Image; + setDescription(description: string): Image; setHeight(height: Number): Image; setLeft(left: Number): Image; setLinkSlide(slideIndex: Integer): Link; @@ -247,6 +268,7 @@ declare namespace GoogleAppsScript { setLinkSlide(slidePosition: SlidePosition): Link; setLinkUrl(url: string): Link; setRotation(angle: Number): Image; + setTitle(title: string): Image; setTop(top: Number): Image; setTransform(transform: AffineTransform): Image; setWidth(width: Number): Image; @@ -267,6 +289,7 @@ declare namespace GoogleAppsScript { getLines(): Line[]; getMaster(): Master; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPageType(): PageType; getPlaceholder(placeholderType: PlaceholderType): PageElement; @@ -285,6 +308,7 @@ declare namespace GoogleAppsScript { insertImage(imageUrl: string): Image; insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startConnectionSite: ConnectionSite, endConnectionSite: ConnectionSite): Line; insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; insertPageElement(pageElement: PageElement): PageElement; insertShape(shape: Shape): Shape; @@ -313,15 +337,20 @@ declare namespace GoogleAppsScript { */ export interface Line { alignOnPage(alignmentPosition: AlignmentPosition): Line; + bringForward(): Line; + bringToFront(): Line; duplicate(): PageElement; + getConnectionSites(): ConnectionSite[]; getDashStyle(): DashStyle; getDescription(): string; getEnd(): Point; getEndArrow(): ArrowStyle; + getEndConnection(): ConnectionSite; getHeight(): Number; getInherentHeight(): Number; getInherentWidth(): Number; getLeft(): Number; + getLineCategory(): LineCategory; getLineFill(): LineFill; getLineType(): LineType; getLink(): Link; @@ -332,24 +361,32 @@ declare namespace GoogleAppsScript { getRotation(): Number; getStart(): Point; getStartArrow(): ArrowStyle; + getStartConnection(): ConnectionSite; getTitle(): string; getTop(): Number; getTransform(): AffineTransform; getWeight(): Number; getWidth(): Number; + isConnector(): boolean; preconcatenateTransform(transform: AffineTransform): Line; remove(): void; removeLink(): void; + reroute(): Line; scaleHeight(ratio: Number): Line; scaleWidth(ratio: Number): Line; select(): void; select(replace: boolean): void; + sendBackward(): Line; + sendToBack(): Line; setDashStyle(style: DashStyle): Line; + setDescription(description: string): Line; setEnd(left: Number, top: Number): Line; setEnd(point: Point): Line; setEndArrow(style: ArrowStyle): Line; + setEndConnection(connectionSite: ConnectionSite): Line; setHeight(height: Number): Line; setLeft(left: Number): Line; + setLineCategory(lineCategory: LineCategory): Line; setLinkSlide(slideIndex: Integer): Link; setLinkSlide(slide: Slide): Link; setLinkSlide(slidePosition: SlidePosition): Link; @@ -358,6 +395,8 @@ declare namespace GoogleAppsScript { setStart(left: Number, top: Number): Line; setStart(point: Point): Line; setStartArrow(style: ArrowStyle): Line; + setStartConnection(connectionSite: ConnectionSite): Line; + setTitle(title: string): Line; setTop(top: Number): Line; setTransform(transform: AffineTransform): Line; setWeight(points: Number): Line; @@ -370,7 +409,7 @@ declare namespace GoogleAppsScript { * The exact LineType created is determined based on the category and how it's routed to * connect to other page elements. */ - export enum LineCategory { STRAIGHT, BENT, CURVED } + export enum LineCategory { UNSUPPORTED, STRAIGHT, BENT, CURVED } /** * Describes the fill of a line or outline @@ -504,6 +543,7 @@ declare namespace GoogleAppsScript { getLayouts(): Layout[]; getLines(): Line[]; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPageType(): PageType; getPlaceholder(placeholderType: PlaceholderType): PageElement; @@ -522,6 +562,7 @@ declare namespace GoogleAppsScript { insertImage(imageUrl: string): Image; insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startConnectionSite: ConnectionSite, endConnectionSite: ConnectionSite): Line; insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; insertPageElement(pageElement: PageElement): PageElement; insertShape(shape: Shape): Shape; @@ -556,6 +597,7 @@ declare namespace GoogleAppsScript { getImages(): Image[]; getLines(): Line[]; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPlaceholder(placeholderType: PlaceholderType): PageElement; getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; @@ -579,6 +621,7 @@ declare namespace GoogleAppsScript { getImages(): Image[]; getLines(): Line[]; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPlaceholder(placeholderType: PlaceholderType): PageElement; getPlaceholder(placeholderType: PlaceholderType, placeholderIndex: Integer): PageElement; @@ -606,6 +649,7 @@ declare namespace GoogleAppsScript { getImages(): Image[]; getLines(): Line[]; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPageType(): PageType; getPlaceholder(placeholderType: PlaceholderType): PageElement; @@ -624,6 +668,7 @@ declare namespace GoogleAppsScript { insertImage(imageUrl: string): Image; insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startConnectionSite: ConnectionSite, endConnectionSite: ConnectionSite): Line; insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; insertPageElement(pageElement: PageElement): PageElement; insertShape(shape: Shape): Shape; @@ -686,7 +731,10 @@ declare namespace GoogleAppsScript { asTable(): Table; asVideo(): Video; asWordArt(): WordArt; + bringForward(): PageElement; + bringToFront(): PageElement; duplicate(): PageElement; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getHeight(): Number; getInherentHeight(): Number; @@ -707,9 +755,13 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): PageElement; select(): void; select(replace: boolean): void; + sendBackward(): PageElement; + sendToBack(): PageElement; + setDescription(description: string): PageElement; setHeight(height: Number): PageElement; setLeft(left: Number): PageElement; setRotation(angle: Number): PageElement; + setTitle(title: string): PageElement; setTop(top: Number): PageElement; setTransform(transform: AffineTransform): PageElement; setWidth(width: Number): PageElement; @@ -836,11 +888,11 @@ declare namespace GoogleAppsScript { getNotesMaster(): NotesMaster; getNotesPageHeight(): Number; getNotesPageWidth(): Number; - getPageElementById(id: string): PageElement; + getPageElementById(id: string): PageElement; getPageHeight(): Number; getPageWidth(): Number; getSelection(): Selection; - getSlideById(id: string): Slide; + getSlideById(id: string): Slide; getSlides(): Slide[]; getUrl(): string; getViewers(): Base.User[]; @@ -903,8 +955,11 @@ declare namespace GoogleAppsScript { */ export interface Shape { alignOnPage(alignmentPosition: AlignmentPosition): Shape; + bringForward(): Shape; + bringToFront(): Shape; duplicate(): PageElement; getBorder(): Border; + getConnectionSites(): ConnectionSite[]; getContentAlignment(): ContentAlignment; getDescription(): string; getFill(): Fill; @@ -940,7 +995,10 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): Shape; select(): void; select(replace: boolean): void; + sendBackward(): Shape; + sendToBack(): Shape; setContentAlignment(contentAlignment: ContentAlignment): Shape; + setDescription(description: string): Shape; setHeight(height: Number): Shape; setLeft(left: Number): Shape; setLinkSlide(slideIndex: Integer): Link; @@ -948,6 +1006,7 @@ declare namespace GoogleAppsScript { setLinkSlide(slidePosition: SlidePosition): Link; setLinkUrl(url: string): Link; setRotation(angle: Number): Shape; + setTitle(title: string): Shape; setTop(top: Number): Shape; setTransform(transform: AffineTransform): Shape; setWidth(width: Number): Shape; @@ -968,8 +1027,11 @@ declare namespace GoogleAppsScript { export interface SheetsChart { alignOnPage(alignmentPosition: AlignmentPosition): SheetsChart; asImage(): Image; + bringForward(): SheetsChart; + bringToFront(): SheetsChart; duplicate(): PageElement; getChartId(): Integer; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getEmbedType(): SheetsChartEmbedType; getHeight(): Number; @@ -995,6 +1057,9 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): SheetsChart; select(): void; select(replace: boolean): void; + sendBackward(): SheetsChart; + sendToBack(): SheetsChart; + setDescription(description: string): SheetsChart; setHeight(height: Number): SheetsChart; setLeft(left: Number): SheetsChart; setLinkSlide(slideIndex: Integer): Link; @@ -1002,6 +1067,7 @@ declare namespace GoogleAppsScript { setLinkSlide(slidePosition: SlidePosition): Link; setLinkUrl(url: string): Link; setRotation(angle: Number): SheetsChart; + setTitle(title: string): SheetsChart; setTop(top: Number): SheetsChart; setTransform(transform: AffineTransform): SheetsChart; setWidth(width: Number): SheetsChart; @@ -1028,6 +1094,7 @@ declare namespace GoogleAppsScript { getLines(): Line[]; getNotesPage(): NotesPage; getObjectId(): string; + getPageElementById(id: string): PageElement; getPageElements(): PageElement[]; getPageType(): PageType; getPlaceholder(placeholderType: PlaceholderType): PageElement; @@ -1046,6 +1113,7 @@ declare namespace GoogleAppsScript { insertImage(imageUrl: string): Image; insertImage(imageUrl: string, left: Number, top: Number, width: Number, height: Number): Image; insertLine(line: Line): Line; + insertLine(lineCategory: LineCategory, startConnectionSite: ConnectionSite, endConnectionSite: ConnectionSite): Line; insertLine(lineCategory: LineCategory, startLeft: Number, startTop: Number, endLeft: Number, endTop: Number): Line; insertPageElement(pageElement: PageElement): PageElement; insertShape(shape: Shape): Shape; @@ -1144,9 +1212,12 @@ declare namespace GoogleAppsScript { alignOnPage(alignmentPosition: AlignmentPosition): Table; appendColumn(): TableColumn; appendRow(): TableRow; + bringForward(): Table; + bringToFront(): Table; duplicate(): PageElement; getCell(rowIndex: Integer, columnIndex: Integer): TableCell; getColumn(columnIndex: Integer): TableColumn; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getHeight(): Number; getInherentHeight(): Number; @@ -1172,9 +1243,13 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): Table; select(): void; select(replace: boolean): void; + sendBackward(): Table; + sendToBack(): Table; + setDescription(description: string): Table; setHeight(height: Number): Table; setLeft(left: Number): Table; setRotation(angle: Number): Table; + setTitle(title: string): Table; setTop(top: Number): Table; setTransform(transform: AffineTransform): Table; setWidth(width: Number): Table; @@ -1343,8 +1418,11 @@ declare namespace GoogleAppsScript { */ export interface Video { alignOnPage(alignmentPosition: AlignmentPosition): Video; + bringForward(): Video; + bringToFront(): Video; duplicate(): PageElement; getBorder(): Border; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getHeight(): Number; getInherentHeight(): Number; @@ -1369,9 +1447,13 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): Video; select(): void; select(replace: boolean): void; + sendBackward(): Video; + sendToBack(): Video; + setDescription(description: string): Video; setHeight(height: Number): Video; setLeft(left: Number): Video; setRotation(angle: Number): Video; + setTitle(title: string): Video; setTop(top: Number): Video; setTransform(transform: AffineTransform): Video; setWidth(width: Number): Video; @@ -1387,7 +1469,10 @@ declare namespace GoogleAppsScript { */ export interface WordArt { alignOnPage(alignmentPosition: AlignmentPosition): WordArt; + bringForward(): WordArt; + bringToFront(): WordArt; duplicate(): PageElement; + getConnectionSites(): ConnectionSite[]; getDescription(): string; getHeight(): Number; getInherentHeight(): Number; @@ -1411,6 +1496,9 @@ declare namespace GoogleAppsScript { scaleWidth(ratio: Number): WordArt; select(): void; select(replace: boolean): void; + sendBackward(): WordArt; + sendToBack(): WordArt; + setDescription(description: string): WordArt; setHeight(height: Number): WordArt; setLeft(left: Number): WordArt; setLinkSlide(slideIndex: Integer): Link; @@ -1418,6 +1506,7 @@ declare namespace GoogleAppsScript { setLinkSlide(slidePosition: SlidePosition): Link; setLinkUrl(url: string): Link; setRotation(angle: Number): WordArt; + setTitle(title: string): WordArt; setTop(top: Number): WordArt; setTransform(transform: AffineTransform): WordArt; setWidth(width: Number): WordArt; diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index 4ac5c84d6b..76a5bd5f22 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -99,7 +99,7 @@ declare namespace GoogleAppsScript { * var range = sheet.getRange("A1:B3"); * var rule = SpreadsheetApp.newConditionalFormatRule() * .whenNumberBetween(1, 10) - * .setBackgroundColor("#FF0000") + * .setBackground("#FF0000") * .setRanges([range]) * .build(); * var rules = sheet.getConditionalFormatRules(); @@ -268,6 +268,61 @@ declare namespace GoogleAppsScript { */ export enum DataValidationCriteria { DATE_AFTER, DATE_BEFORE, DATE_BETWEEN, DATE_EQUAL_TO, DATE_IS_VALID_DATE, DATE_NOT_BETWEEN, DATE_ON_OR_AFTER, DATE_ON_OR_BEFORE, NUMBER_BETWEEN, NUMBER_EQUAL_TO, NUMBER_GREATER_THAN, NUMBER_GREATER_THAN_OR_EQUAL_TO, NUMBER_LESS_THAN, NUMBER_LESS_THAN_OR_EQUAL_TO, NUMBER_NOT_BETWEEN, NUMBER_NOT_EQUAL_TO, TEXT_CONTAINS, TEXT_DOES_NOT_CONTAIN, TEXT_EQUAL_TO, TEXT_IS_VALID_EMAIL, TEXT_IS_VALID_URL, VALUE_IN_LIST, VALUE_IN_RANGE, CUSTOM_FORMULA, CHECKBOX } + /** + * Access and modify developer metadata. To create new developer metadata use Range.addDeveloperMetadata(key), Sheet.addDeveloperMetadata(key), or Spreadsheet.addDeveloperMetadata(key). + */ + export interface DeveloperMetadata { + getId(): Integer; + getKey(): string; + getLocation(): DeveloperMetadataLocation; + getValue(): string; + getVisibility(): DeveloperMetadataVisibility; + moveToColumn(column: Range): DeveloperMetadata; + moveToRow(row: Range): DeveloperMetadata; + moveToSheet(sheet: Sheet): DeveloperMetadata; + moveToSpreadsheet(): DeveloperMetadata; + remove(): void; + setKey(key: string): DeveloperMetadata; + setValue(value: string): DeveloperMetadata; + setVisibility(visibility: DeveloperMetadataVisibility): DeveloperMetadata; + } + + /** + * Search for developer metadata in a spreadsheet. To create new developer metadata finder use + * Range.createDeveloperMetadataFinder(), Sheet.createDeveloperMetadataFinder(), + * or Spreadsheet.createDeveloperMetadataFinder(). + */ + export interface DeveloperMetadataFinder { + find(): DeveloperMetadata[]; + onIntersectingLocations(): DeveloperMetadataFinder; + withId(id: Integer): DeveloperMetadataFinder; + withKey(key: string): DeveloperMetadataFinder; + withLocationType(locationType: DeveloperMetadataLocationType): DeveloperMetadataFinder; + withValue(value: string): DeveloperMetadataFinder; + withVisibility(visibility: DeveloperMetadataVisibility): DeveloperMetadataFinder; + } + + /** + * Access developer metadata location information. + */ + export interface DeveloperMetadataLocation { + getColumn(): Range; + getLocationType(): DeveloperMetadataLocationType; + getRow(): Range; + getSheet(): Sheet; + getSpreadsheet(): Spreadsheet; + } + + /** + * An enumeration of the types of developer metadata location types. + */ + export enum DeveloperMetadataLocationType { SPREADSHEET, SHEET, ROW, COLUMN } + + /** + * An enumeration of the types of developer metadata visibility. + */ + export enum DeveloperMetadataVisibility { DOCUMENT, PROJECT } + /** * An enumeration of possible directions along which data can be stored in a spreadsheet. */ @@ -896,6 +951,36 @@ declare namespace GoogleAppsScript { setRange(range: Range): NamedRange; } + /** + * Represents an image over the grid in a spreadsheet. + */ + export interface OverGridImage { + assignScript(functionName: string): OverGridImage; + getAltTextDescription(): string; + getAltTextTitle(): string; + getAnchorCell(): Range; + getAnchorCellXOffset(): Integer; + getAnchorCellYOffset(): Integer; + getHeight(): Integer; + getInherentHeight(): Integer; + getInherentWidth(): Integer; + getScript(): string; + getSheet(): Sheet; + getUrl(): string; + getWidth(): Integer; + remove(): void; + replace(blob: Base.BlobSource): OverGridImage; + replace(url: string): OverGridImage; + resetSize(): OverGridImage; + setAltTextDescription(description: string): OverGridImage; + setAltTextTitle(title: string): OverGridImage; + setAnchorCell(cell: Range): OverGridImage; + setAnchorCellXOffset(offset: Integer): OverGridImage; + setAnchorCellYOffset(offset: Integer): OverGridImage; + setHeight(height: Integer): OverGridImage; + setWidth(width: Integer): OverGridImage; + } + /** * * Deprecated. For spreadsheets created in the newer version of Google Sheets, use the more powerful @@ -1091,6 +1176,10 @@ declare namespace GoogleAppsScript { export interface Range { activate(): Range; activateAsCurrentCell(): Range; + addDeveloperMetadata(key: string): Range; + addDeveloperMetadata(key: string, visibility: DeveloperMetadataVisibility): Range; + addDeveloperMetadata(key: string, value: string): Range; + addDeveloperMetadata(key: string, value: string, visibility: DeveloperMetadataVisibility): Range; applyColumnBanding(): Banding; applyColumnBanding(bandingTheme: BandingTheme): Banding; applyColumnBanding(bandingTheme: BandingTheme, showHeader: boolean, showFooter: boolean): Banding; @@ -1115,6 +1204,7 @@ declare namespace GoogleAppsScript { copyTo(destination: Range, options: Object): void; copyValuesToRange(gridId: Integer, column: Integer, columnEnd: Integer, row: Integer, rowEnd: Integer): void; copyValuesToRange(sheet: Sheet, column: Integer, columnEnd: Integer, row: Integer, rowEnd: Integer): void; + createDeveloperMetadataFinder(): DeveloperMetadataFinder; createFilter(): Filter; createPivotTable(sourceData: Range): PivotTable; deleteCells(shiftDimension: Dimension): void; @@ -1130,6 +1220,7 @@ declare namespace GoogleAppsScript { getDataTable(firstRowIsHeader: boolean): Charts.DataTable; getDataValidation(): DataValidation; getDataValidations(): DataValidation[][]; + getDeveloperMetadata(): DeveloperMetadata[]; getDisplayValue(): string; getDisplayValues(): string[][]; getFilter(): Filter; @@ -1178,7 +1269,7 @@ declare namespace GoogleAppsScript { getWrap(): boolean; getWrapStrategies(): WrapStrategy[][]; getWrapStrategy(): WrapStrategy; - getWraps(): Boolean[][]; + getWraps(): boolean[][]; insertCells(shiftDimension: Dimension): Range; isBlank(): boolean; isEndColumnBounded(): boolean; @@ -1328,6 +1419,10 @@ declare namespace GoogleAppsScript { */ export interface Sheet { activate(): Sheet; + addDeveloperMetadata(key: string): Sheet; + addDeveloperMetadata(key: string, visibility: DeveloperMetadataVisibility): Sheet; + addDeveloperMetadata(key: string, value: string): Sheet; + addDeveloperMetadata(key: string, value: string, visibility: DeveloperMetadataVisibility): Sheet; appendRow(rowContents: Object[]): Sheet; autoResizeColumn(columnPosition: Integer): Sheet; autoResizeColumns(startColumn: Integer, numColumns: Integer): Sheet; @@ -1341,6 +1436,7 @@ declare namespace GoogleAppsScript { collapseAllColumnGroups(): Sheet; collapseAllRowGroups(): Sheet; copyTo(spreadsheet: Spreadsheet): Sheet; + createDeveloperMetadataFinder(): DeveloperMetadataFinder; deleteColumn(columnPosition: Integer): Sheet; deleteColumns(columnPosition: Integer, howMany: Integer): void; deleteRow(rowPosition: Integer): Sheet; @@ -1361,10 +1457,12 @@ declare namespace GoogleAppsScript { getConditionalFormatRules(): ConditionalFormatRule[]; getCurrentCell(): Range; getDataRange(): Range; + getDeveloperMetadata(): DeveloperMetadata[]; getFilter(): Filter; getFormUrl(): string; getFrozenColumns(): Integer; getFrozenRows(): Integer; + getImages(): OverGridImage[]; getIndex(): Integer; getLastColumn(): Integer; getLastRow(): Integer; @@ -1404,17 +1502,20 @@ declare namespace GoogleAppsScript { insertColumns(columnIndex: Integer, numColumns: Integer): void; insertColumnsAfter(afterPosition: Integer, howMany: Integer): Sheet; insertColumnsBefore(beforePosition: Integer, howMany: Integer): Sheet; - insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer): void; - insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): void; - insertImage(url: string, column: Integer, row: Integer): void; - insertImage(url: string, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): void; + insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer): OverGridImage; + insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): OverGridImage; + insertImage(url: string, column: Integer, row: Integer): OverGridImage; + insertImage(url: string, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): OverGridImage; insertRowAfter(afterPosition: Integer): Sheet; insertRowBefore(beforePosition: Integer): Sheet; insertRows(rowIndex: Integer): void; insertRows(rowIndex: Integer, numRows: Integer): void; insertRowsAfter(afterPosition: Integer, howMany: Integer): Sheet; insertRowsBefore(beforePosition: Integer, howMany: Integer): Sheet; + isColumnHiddenByUser(columnPosition: Integer): boolean; isRightToLeft(): boolean; + isRowHiddenByFilter(rowPosition: Integer): boolean; + isRowHiddenByUser(rowPosition: Integer): boolean; isSheetHidden(): boolean; moveColumns(columnSpec: Range, destinationIndex: Integer): void; moveRows(rowSpec: Range, destinationIndex: Integer): void; @@ -1458,6 +1559,10 @@ declare namespace GoogleAppsScript { * collaborators. */ export interface Spreadsheet { + addDeveloperMetadata(key: string): Spreadsheet; + addDeveloperMetadata(key: string, visibility: DeveloperMetadataVisibility): Spreadsheet; + addDeveloperMetadata(key: string, value: string): Spreadsheet; + addDeveloperMetadata(key: string, value: string, visibility: DeveloperMetadataVisibility): Spreadsheet; addEditor(emailAddress: string): Spreadsheet; addEditor(user: Base.User): Spreadsheet; addEditors(emailAddresses: string[]): Spreadsheet; @@ -1468,6 +1573,7 @@ declare namespace GoogleAppsScript { appendRow(rowContents: Object[]): Sheet; autoResizeColumn(columnPosition: Integer): Sheet; copy(name: string): Spreadsheet; + createDeveloperMetadataFinder(): DeveloperMetadataFinder; deleteActiveSheet(): Sheet; deleteColumn(columnPosition: Integer): Sheet; deleteColumns(columnPosition: Integer, howMany: Integer): void; @@ -1485,11 +1591,13 @@ declare namespace GoogleAppsScript { getColumnWidth(columnPosition: Integer): Integer; getCurrentCell(): Range; getDataRange(): Range; + getDeveloperMetadata(): DeveloperMetadata[]; getEditors(): Base.User[]; getFormUrl(): string; getFrozenColumns(): Integer; getFrozenRows(): Integer; getId(): string; + getImages(): OverGridImage[]; getLastColumn(): Integer; getLastRow(): Integer; getName(): string; @@ -1517,10 +1625,10 @@ declare namespace GoogleAppsScript { insertColumnBefore(beforePosition: Integer): Sheet; insertColumnsAfter(afterPosition: Integer, howMany: Integer): Sheet; insertColumnsBefore(beforePosition: Integer, howMany: Integer): Sheet; - insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer): void; - insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): void; - insertImage(url: string, column: Integer, row: Integer): void; - insertImage(url: string, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): void; + insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer): OverGridImage; + insertImage(blobSource: Base.BlobSource, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): OverGridImage; + insertImage(url: string, column: Integer, row: Integer): OverGridImage; + insertImage(url: string, column: Integer, row: Integer, offsetX: Integer, offsetY: Integer): OverGridImage; insertRowAfter(afterPosition: Integer): Sheet; insertRowBefore(beforePosition: Integer): Sheet; insertRowsAfter(afterPosition: Integer, howMany: Integer): Sheet; @@ -1533,6 +1641,9 @@ declare namespace GoogleAppsScript { insertSheet(sheetName: string, sheetIndex: Integer): Sheet; insertSheet(sheetName: string, sheetIndex: Integer, options: Object): Sheet; insertSheet(sheetName: string, options: Object): Sheet; + isColumnHiddenByUser(columnPosition: Integer): boolean; + isRowHiddenByFilter(rowPosition: Integer): boolean; + isRowHiddenByUser(rowPosition: Integer): boolean; moveActiveSheet(pos: Integer): void; removeEditor(emailAddress: string): Spreadsheet; removeEditor(user: Base.User): Spreadsheet; @@ -1582,6 +1693,8 @@ declare namespace GoogleAppsScript { BorderStyle: typeof BorderStyle; CopyPasteType: typeof CopyPasteType; DataValidationCriteria: typeof DataValidationCriteria; + DeveloperMetadataLocationType: typeof DeveloperMetadataLocationType; + DeveloperMetadataVisibility: typeof DeveloperMetadataVisibility; Dimension: typeof Dimension; Direction: typeof Direction; GroupControlTogglePosition: typeof GroupControlTogglePosition; diff --git a/types/google-apps-script/google-apps-script.utilities.d.ts b/types/google-apps-script/google-apps-script.utilities.d.ts index 272c341b6c..922e31544a 100644 --- a/types/google-apps-script/google-apps-script.utilities.d.ts +++ b/types/google-apps-script/google-apps-script.utilities.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2018-12-26 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,7 +14,7 @@ declare namespace GoogleAppsScript { export enum Charset { US_ASCII, UTF_8 } /** - * Selector of Digest algorithm + * Selector of Digest algorithm. */ export enum DigestAlgorithm { MD2, MD5, SHA_1, SHA_256, SHA_384, SHA_512 } @@ -23,6 +23,11 @@ declare namespace GoogleAppsScript { */ export enum MacAlgorithm { HMAC_MD5, HMAC_SHA_1, HMAC_SHA_256, HMAC_SHA_384, HMAC_SHA_512 } + /** + * Selector of RSA algorithm + */ + export enum RsaAlgorithm { RSA_SHA_1, RSA_SHA_256 } + /** * This service provides utilities for string encoding/decoding, date formatting, JSON manipulation, * and other miscellaneous tasks. @@ -31,6 +36,7 @@ declare namespace GoogleAppsScript { Charset: typeof Charset; DigestAlgorithm: typeof DigestAlgorithm; MacAlgorithm: typeof MacAlgorithm; + RsaAlgorithm: typeof RsaAlgorithm; base64Decode(encoded: string): Byte[]; base64Decode(encoded: string, charset: Charset): Byte[]; base64DecodeWebSafe(encoded: string): Byte[]; @@ -50,8 +56,12 @@ declare namespace GoogleAppsScript { computeHmacSignature(algorithm: MacAlgorithm, value: Byte[], key: Byte[]): Byte[]; computeHmacSignature(algorithm: MacAlgorithm, value: string, key: string): Byte[]; computeHmacSignature(algorithm: MacAlgorithm, value: string, key: string, charset: Charset): Byte[]; + computeRsaSha1Signature(value: string, key: string): Byte[]; + computeRsaSha1Signature(value: string, key: string, charset: Charset): Byte[]; computeRsaSha256Signature(value: string, key: string): Byte[]; computeRsaSha256Signature(value: string, key: string, charset: Charset): Byte[]; + computeRsaSignature(algorithm: RsaAlgorithm, value: string, key: string): Byte[]; + computeRsaSignature(algorithm: RsaAlgorithm, value: string, key: string, charset: Charset): Byte[]; formatDate(date: Date, timeZone: string, format: string): string; formatString(template: string, ...args: Object[]): string; getUuid(): string; @@ -80,4 +90,5 @@ declare namespace GoogleAppsScript { declare var Charset: GoogleAppsScript.Utilities.Charset; declare var DigestAlgorithm: GoogleAppsScript.Utilities.DigestAlgorithm; declare var MacAlgorithm: GoogleAppsScript.Utilities.MacAlgorithm; +declare var RsaAlgorithm: GoogleAppsScript.Utilities.RsaAlgorithm; declare var Utilities: GoogleAppsScript.Utilities.Utilities; From 3db4c59326d5bebca83fa95ce623241222e1cb2f Mon Sep 17 00:00:00 2001 From: PopGoesTheWza <32041843+PopGoesTheWza@users.noreply.github.com> Date: Wed, 26 Dec 2018 16:35:26 +0100 Subject: [PATCH 007/225] Update google-apps-script.forms.d.ts --- types/google-apps-script/google-apps-script.forms.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/google-apps-script/google-apps-script.forms.d.ts b/types/google-apps-script/google-apps-script.forms.d.ts index 33df1975c7..2f4508a956 100644 --- a/types/google-apps-script/google-apps-script.forms.d.ts +++ b/types/google-apps-script/google-apps-script.forms.d.ts @@ -151,6 +151,9 @@ declare namespace GoogleAppsScript { * checkBoxItem.setValidation(checkBoxValidation); */ export interface CheckboxValidation { + requireSelectAtLeast(number: Integer): CheckboxValidation; + requireSelectAtMost(number: Integer): CheckboxValidation; + requireSelectExactly(number: Integer): CheckboxValidation; } /** From eaef39d87d42500ef33fe85c2c10ad7b8f8e6815 Mon Sep 17 00:00:00 2001 From: PopGoesTheWza Date: Wed, 26 Dec 2018 17:08:18 +0100 Subject: [PATCH 008/225] add data-studio, rename card-service, order as per ref page --- .../google-apps-script.card.d.ts | 660 ------------------ types/google-apps-script/index.d.ts | 13 +- 2 files changed, 7 insertions(+), 666 deletions(-) delete mode 100644 types/google-apps-script/google-apps-script.card.d.ts diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts deleted file mode 100644 index 60a8bb9d37..0000000000 --- a/types/google-apps-script/google-apps-script.card.d.ts +++ /dev/null @@ -1,660 +0,0 @@ -// Type definitions for Google Apps Script 2018-07-11 -// Project: https://developers.google.com/apps-script/ -// Definitions by: motemen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace GoogleAppsScript { - export module Card { - /** - * An action that enables interactivity within UI elements. The action does not happen directly on - * the client but rather invokes an Apps Script callback function with optional parameters. - * - * var image = CardService.newImage() - * .setOnClickAction(CardService.newAction() - * .setFunctionName("handleImageClick") - * .setParameters({imageSrc: 'carImage'})); - */ - export interface Action { - setFunctionName(functionName: string): Action; - setLoadIndicator(loadIndicator: LoadIndicator): Action; - setParameters(parameters: Object): Action; - setMethodName(functionName: string): Action; - } - - /** - * The response object that may be returned from a callback function (e.g., a form response handler) - * to perform one or more actions on the client. Some combinations of actions are not supported. - * - * // An action that opens a link - * var actionResponse = CardService.newActionResponseBuilder() - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://www.google.com")) - * .build(); - * - * // An action that shows a notification. - * var actionResponse = CardService.newActionResponseBuilder() - * .setNotification(CardService.newNotification() - * .setType(CardService.Notification.INFO) - * .setText("Some info to display to user")) - * .build(); - * - * // An action that shows an additional card. It also sets a flag to indicate that the original - * // state data has changed. - * - * var cardBuilder = CardService.newCardBuilder(); - * // Build card ... - * var actionResponse = CardService.newActionResponseBuilder() - * .setNavigation(CardService.newNavigation() - * .pushCard(cardBuilder.build())) - * .setStateChanged(true) - * .build(); - */ - export interface ActionResponse { - printJson(): string; - } - - /** - * A builder for ActionResponse objects. - */ - export interface ActionResponseBuilder { - build(): ActionResponse; - setNavigation(navigation: Navigation): ActionResponseBuilder; - setNotification(notification: Notification): ActionResponseBuilder; - setOpenLink(openLink: OpenLink): ActionResponseBuilder; - setStateChanged(stateChanged: boolean): ActionResponseBuilder; - } - - /** - * An authorization action that will send the user to the AuthorizationUrl when clicked. - * - * CardService.newAuthorizationAction() - * .setAuthorizationUrl("http://google.com/"); - */ - export interface AuthorizationAction { - setAuthorizationUrl(authorizationUrl: string): AuthorizationAction; - } - - /** - * An error that can be returned to trigger an authorization card to be shown to the user. - * - * CardService.newAuthorizationException() - * .setAuthorizationUrl("http://auth.com/") - * .setResourceDisplayName("Example Resource") - * .throwException(); - */ - export interface AuthorizationException { - printJson(): string; - setAuthorizationUrl(authUrl: string): AuthorizationException; - setCustomUiCallback(callback: string): AuthorizationException; - setResourceDisplayName(name: string): AuthorizationException; - throwException(): void; - } - - /** - * A base class for all buttons. - */ - export interface Button { - setAuthorizationAction(action: AuthorizationAction): Button; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): Button; - setOnClickAction(action: Action): Button; - setOnClickOpenLinkAction(action: Action): Button; - setOpenLink(openLink: OpenLink): Button; - } - - /** - * Holds a set of Button objects that are displayed in a row. - * - * var textButton = CardService.newTextButton(); - * // Finish building the text button... - * - * var imageButton = CardService.newImageButton(); - * // Finish building the image button... - * - * var buttonSet = CardService.newButtonSet() - * .addButton(textButton) - * .addButton(imageButton); - */ - export interface ButtonSet { - addButton(button: Button): ButtonSet; - } - - /** - * A context card that represents a single view in the - * UI. - * - * var cardSection = CardService.newCardSection(); - * // Finish building the card section ... - * - * var card = CardService.newCardBuilder() - * .setName("Card name") - * .setHeader(CardService.newCardHeader().setTitle("Card title")) - * .addSection(cardSection) - * .build(); - */ - export interface Card { - printJson(): string; - } - - /** - * A clickable menu item that is added to the card header menu. - * - * var action = CardService.newAction(); - * // Finish building the action... - * - * var cardAction = CardService.newCardAction() - * .setText("Card action") - * .setOnClickAction(action); - */ - export interface CardAction { - setAuthorizationAction(action: AuthorizationAction): CardAction; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): CardAction; - setOnClickAction(action: Action): CardAction; - setOnClickOpenLinkAction(action: Action): CardAction; - setOpenLink(openLink: OpenLink): CardAction; - setText(text: string): CardAction; - } - - /** - * A builder for Card objects. - */ - export interface CardBuilder { - addCardAction(cardAction: CardAction): CardBuilder; - addSection(section: CardSection): CardBuilder; - build(): Card; - setHeader(cardHeader: CardHeader): CardBuilder; - setName(name: string): CardBuilder; - } - - /** - * The header of a Card. - * - * var cardHeader = CardService.newCardHeader() - * .setTitle("Card header title") - * .setSubtitle("Card header subtitle") - * .setImageStyle(CardService.ImageStyle.CIRCLE) - * .setImageUrl("https://image.png"); - */ - export interface CardHeader { - setImageAltText(imageAltText: string): CardHeader; - setImageStyle(imageStyle: ImageStyle): CardHeader; - setImageUrl(imageUrl: string): CardHeader; - setSubtitle(subtitle: string): CardHeader; - setTitle(title: string): CardHeader; - } - - /** - * A card section holds groups of widgets and provides visual separation between them. - * - * var image = CardService.newImage(); - * // Build image ... - * var textParagraph = CardService.newTextParagraph(); - * // Build text paragraph ... - * - * var cardSection = CardService.newCardSection() - * .setHeader("Section header") - * .addWidget(image) - * .addWidget(textParagraph); - */ - export interface CardSection { - addWidget(widget: Widget): CardSection; - setCollapsible(collapsible: boolean): CardSection; - setHeader(header: string): CardSection; - setNumUncollapsibleWidgets(numUncollapsibleWidgets: Integer): CardSection; - } - - /** - * CardService provides the ability to create generic cards used across different Google - * extensibility products, such as Gmail add-ons. - * - * Currently you can only use this service to construct Gmail add-ons. - * - * return CardService.newCardBuilder() - * .setHeader(CardService.newCardHeader().setTitle("CardTitle")) - * .build(); - * - * Or you can return multiple Cards like so: - * - * return [ - * CardService.newCardBuilder().build(), - * CardService.newCardBuilder().build(), - * CardService.newCardBuilder().build() - * ] - * - * The following shows how you could define a card with a header, text, an image and a menu item: - * - * function createWidgetDemoCard() { - * return CardService - * .newCardBuilder() - * .setHeader( - * CardService.newCardHeader() - * .setTitle('Widget demonstration') - * .setSubtitle('Check out these widgets') - * .setImageStyle(CardService.ImageStyle.SQUARE) - * .setImageUrl( - * 'https://www.example.com/images/headerImage.png')) - * .addSection( - * CardService.newCardSection() - * .setHeader('Simple widgets') // optional - * .addWidget(CardService.newTextParagraph().setText( - * 'These widgets are display-only. ' + - * 'A text paragraph can have multiple lines and ' + - * 'formatting.')) - * .addWidget(CardService.newImage().setImageUrl( - * 'https://www.example.com/images/mapsImage.png'))) - * .addCardAction(CardService.newCardAction().setText('Gmail').setOpenLink( - * CardService.newOpenLink().setUrl('https://mail.google.com/mail'))) - * .build(); - * } - */ - export interface CardService { - ComposedEmailType: typeof ComposedEmailType; - Icon: typeof Icon; - ImageStyle: typeof ImageStyle; - LoadIndicator: typeof LoadIndicator; - NotificationType: typeof NotificationType; - OnClose: typeof OnClose; - OpenAs: typeof OpenAs; - SelectionInputType: typeof SelectionInputType; - newAction(): Action; - newActionResponseBuilder(): ActionResponseBuilder; - newAuthorizationAction(): AuthorizationAction; - newAuthorizationException(): AuthorizationException; - newButtonSet(): ButtonSet; - newCardAction(): CardAction; - newCardBuilder(): CardBuilder; - newCardHeader(): CardHeader; - newCardSection(): CardSection; - newComposeActionResponseBuilder(): ComposeActionResponseBuilder; - newImage(): Image; - newImageButton(): ImageButton; - newKeyValue(): KeyValue; - newNavigation(): Navigation; - newNotification(): Notification; - newOpenLink(): OpenLink; - newSelectionInput(): SelectionInput; - newSuggestions(): Suggestions; - newSuggestionsResponseBuilder(): SuggestionsResponseBuilder; - newSwitch(): Switch; - newTextButton(): TextButton; - newTextInput(): TextInput; - newTextParagraph(): TextParagraph; - newUniversalActionResponseBuilder(): UniversalActionResponseBuilder; - } - - /** - * The response object that may be returned from a callback method for compose action in a Gmail add-on. - * - * var composeActionResponse = CardService.newComposeActionResponseBuilder() - * .setGmailDraft(GmailApp.createDraft("recipient", "subject", "body")) - * .build(); - */ - export interface ComposeActionResponse { - printJson(): string; - } - - /** - * A builder for ComposeActionResponse objects. - */ - export interface ComposeActionResponseBuilder { - build(): ComposeActionResponse; - setGmailDraft(draft: Gmail.GmailDraft): ComposeActionResponseBuilder; - } - - /** - * An enum value that specifies whether the composed email is a standalone or reply draft. - */ - export enum ComposedEmailType { REPLY_AS_DRAFT, STANDALONE_DRAFT } - - /** - * Predefined icons that can be used in various UI objects, such as ImageButton or KeyValue widgets. - */ - export enum Icon { NONE, AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DOLLAR, DESCRIPTION, EMAIL, EVENT_PERFORMER, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, OFFER, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } - - /** - * A widget that shows a single image. - * - * var image = CardService.newImage().setAltText("A nice image").setImageUrl("https://image.png"); - */ - export interface Image { - setAltText(altText: string): Image; - setAuthorizationAction(action: AuthorizationAction): Image; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): Image; - setImageUrl(url: string): Image; - setOnClickAction(action: Action): Image; - setOnClickOpenLinkAction(action: Action): Image; - setOpenLink(openLink: OpenLink): Image; - } - - /** - * A ImageButton with an image displayed on it. - * - * var imageButton = CardService.newImageButton() - * .setAltText("An image button with an airplane icon.") - * .setIcon(CardService.Icon.AIRPLANE) - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://airplane.com")); - */ - export interface ImageButton { - setAltText(altText: string): ImageButton; - setAuthorizationAction(action: AuthorizationAction): ImageButton; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): ImageButton; - setIcon(icon: Icon): ImageButton; - setIconUrl(url: string): ImageButton; - setOnClickAction(action: Action): ImageButton; - setOnClickOpenLinkAction(action: Action): ImageButton; - setOpenLink(openLink: OpenLink): ImageButton; - } - - /** - * An enum that defines an image cropping style. - */ - export enum ImageStyle { SQUARE, CIRCLE } - - /** - * A widget that displays one or more "keys" around a text "value". The possible keys include an - * icon, a label above and a label below. Setting the text content and one of the keys is required - * using setContent(text) and one of setIcon(icon), setIconUrl(url), setTopLabel(text), - * or setBottomLabel(text). - * - * var imageKeyValue = CardService.newKeyValue() - * .setIconUrl("https://icon.png") - * .setContent("KeyValue widget with an image on the left and text on the right"); - * - * var textKeyValue = CardService.newKeyValue() - * .setTopLabel("Text key") - * .setContent("KeyValue widget with text key on top and cotent below"); - * - * var multilineKeyValue = CardService.newKeyValue() - * .setTopLabel("Top label - single line)") - * .setContent("Content can be multiple lines") - * .setMultiline(true) - * .setBottomLabel("Bottom label - single line"); - */ - export interface KeyValue { - setAuthorizationAction(action: AuthorizationAction): KeyValue; - setBottomLabel(text: string): KeyValue; - setButton(button: Button): KeyValue; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): KeyValue; - setContent(text: string): KeyValue; - setIcon(icon: Icon): KeyValue; - setIconAltText(altText: string): KeyValue; - setIconUrl(url: string): KeyValue; - setMultiline(multiline: boolean): KeyValue; - setOnClickAction(action: Action): KeyValue; - setOnClickOpenLinkAction(action: Action): KeyValue; - setOpenLink(openLink: OpenLink): KeyValue; - setSwitch(switchToSet: Switch): KeyValue; - setTopLabel(text: string): KeyValue; - } - - /** - * An enum type that specifies the type of loading or progress indicator to display while an Action is being processed. - */ - export enum LoadIndicator { SPINNER, NONE } - - /** - * A helper object that controls card navigation. See the card navigation guide for more details. - */ - export interface Navigation { - popCard(): Navigation; - popToNamedCard(cardName: string): Navigation; - popToRoot(): Navigation; - printJson(): string; - pushCard(card: Card): Navigation; - updateCard(card: Card): Navigation; - } - - /** - * A notification shown to the user as a response to interacting with a UI element. - * - * var action = CardService.newAction().setFunctionName("notificationCallback"); - * CardService.newTextButton().setText('Save').setOnClickAction(action); - * - * // ... - * - * function notificationCallback() { - * return CardService.newActionResponseBuilder() - * .setNotification(CardService.newNotification() - * .setType(CardService.NotificationType.WARNING) - * .setText("Some info to display to user")) - * .build(); - * } - */ - export interface Notification { - setText(text: string): Notification; - setType(type: NotificationType): Notification; - } - - /** - * Type of notification to show. - */ - export enum NotificationType { INFO, ERROR, WARNING } - - /** - * An enum that specifies what to do when a URL opened through an OpenLink is closed. - * - * When a link is opened, the client either forgets about it or waits until the window is closed. - * The implementation depends on the client platform capabilities. OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, - * OnClose takes precedence. - */ - export enum OnClose { NOTHING, RELOAD_ADD_ON } - - /** - * An enum that specifies how to open a URL. - * - * The client can open a URL as either a full size window (if that is the frame used by the - * client), or an overlay (such as a pop-up). The implementation depends on the client platform - * capabilities, and the value selected may be ignored if the client does not support it. FULL_SIZE is supported by all clients. - * - * Using OnClose may cause OpenAs to be ignored; if the client platform cannot - * support both selected values together, OnClose takes precedence. - */ - export enum OpenAs { FULL_SIZE, OVERLAY } - - /** - * Represents an action to open a link with some options. - * - * // A button that opens as a link in an overlay and - * // requires a reload when closed. - * var button = CardService.newTextButton() - * .setText("This button opens a link in an overlay window") - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://www.google.com") - * .setOpenAs(CardService.OpenAs.OVERLAY) - * .setOnClose(CardService.OnClose.RELOAD_ADD_ON)); - * - * // An action response that opens a link in full screen and - * // requires no action when closed. - * var actionResponse = CardService.newActionResponseBuilder() - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://www.google.com") - * .setOpenAs(CardService.OpenAs.FULL_SIZE) - * .setOnClose(CardService.OnClose.NOTHING)); - * .build(); - */ - export interface OpenLink { - setOnClose(onClose: OnClose): OpenLink; - setOpenAs(openAs: OpenAs): OpenLink; - setUrl(url: string): OpenLink; - } - - /** - * An input field that allows choosing between a set of predefined options. - * - * var checkboxGroup = CardService.newSelectionInput() - * .setType(CardService.SelectionInputType.CHECK_BOX) - * .setTitle("A group of checkboxes. Multiple selections are allowed.") - * .setFieldName("checkbox_field") - * .addItem("checkbox one title", "checkbox_one_value", false) - * .addItem("checkbox two title", "checkbox_two_value", true) - * .addItem("checkbox three title", "checkbox_three_value", false) - * .setOnChangeAction(CardService.newAction() - * .setFunctionName("handleCheckboxChange")); - * - * var radioGroup = CardService.newSelectionInput() - * .setType(CardService.SelectionInputType.RADIO_BUTTON) - * .setTitle("A group of radio buttons. Only a single selection is allowed.") - * .setFieldName("checkbox_field") - * .addItem("radio button one title", "radio_one_value", true) - * .addItem("radio button two title", "radio_two_value", true) - * .addItem("radio button three title", "radio_three_value", false); - */ - export interface SelectionInput { - addItem(text: Object, value: Object, selected: boolean): SelectionInput; - setFieldName(fieldName: string): SelectionInput; - setOnChangeAction(action: Action): SelectionInput; - setTitle(title: string): SelectionInput; - setType(type: SelectionInputType): SelectionInput; - } - - /** - * Type of selection input. - */ - export enum SelectionInputType { CHECK_BOX, RADIO_BUTTON, DROPDOWN } - - /** - * Autocomplete suggestions to supplement a TextInput widget. - * - * var textInput = CardService.newTextInput() - * .setSuggestions(CardService.newSuggestions() - * .addSuggestion("First suggestion") - * .addSuggestion("Second suggestion")) - */ - export interface Suggestions { - addSuggestion(suggestion: string): Suggestions; - addSuggestions(suggestions: Object[]): Suggestions; - } - - /** - * A response object that can be returned from a suggestions callback function. This is used with - * TextInput widgets that implement autocomplete. - * - * var suggestionsResponse = CardService.newSuggestionsResponseBuilder() - * .setSuggestions(CardService.newSuggestions() - * .addSuggestion("First suggestion") - * .addSuggestion("Second suggestion")) - * .build(); - */ - export interface SuggestionsResponse { - printJson(): string; - } - - /** - * A builder for SuggestionsResponse objects. - */ - export interface SuggestionsResponseBuilder { - build(): SuggestionsResponse; - setSuggestions(suggestions: Suggestions): SuggestionsResponseBuilder; - } - - /** - * A UI element that supports being toggled on or off. This can only be used within a KeyValue widget. - * - * var switchKeyValue = CardService.newKeyValue() - * .setTopLabel("Switch key value widget label") - * .setContent("This is a key value widget with a switch on the right") - * .setSwitch(CardService.newSwitch() - * .setFieldName("form_input_switch_key") - * .setValue("form_input_switch_value") - * .setOnChangeAction(CardService.newAction() - * .setFunctionName("handleSwitchChange"))); - */ - export interface Switch { - setFieldName(fieldName: string): Switch; - setOnChangeAction(action: Action): Switch; - setSelected(selected: boolean): Switch; - setValue(value: string): Switch; - } - - /** - * A TextButton with a text label. - * - * var textButton = CardService.newTextButton() - * .setText("Open Link") - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://www.google.com")); - */ - export interface TextButton { - setAuthorizationAction(action: AuthorizationAction): TextButton; - setComposeAction(action: Action, composedEmailType: ComposedEmailType): TextButton; - setOnClickAction(action: Action): TextButton; - setOnClickOpenLinkAction(action: Action): TextButton; - setOpenLink(openLink: OpenLink): TextButton; - setText(text: string): TextButton; - } - - /** - * A input field widget that accepts text input. - * - * var textInput = CardService.newTextInput() - * .setFieldName("text_input_form_input_key") - * .setTitle("Text input title") - * .setHint("Text input hint"); - */ - export interface TextInput { - setFieldName(fieldName: string): TextInput; - setHint(hint: string): TextInput; - setMultiline(multiline: boolean): TextInput; - setOnChangeAction(action: Action): TextInput; - setSuggestions(suggestions: Suggestions): TextInput; - setSuggestionsAction(suggestionsAction: Action): TextInput; - setTitle(title: string): TextInput; - setValue(value: string): TextInput; - } - - /** - * A widget that displays text and supports basic HTML formatting. - * - * var textParagraph = CardService.newTextParagraph() - * .setText("This is a text paragraph widget. Multiple lines are allowed if needed."); - */ - export interface TextParagraph { - setText(text: string): TextParagraph; - } - - /** - * The response object that may be returned from a method that creates universal action. - * - * // A universal action that opens a link. - * var openLinkUniversalAction = CardService.newUniversalActionResponseBuilder() - * .setOpenLink(CardService.newOpenLink() - * .setUrl("https://www.google.com")) - * .build(); - * - * var cardBuilder1 = CardService.newCardBuilder(); - * var cardBuilder2 = CardService.newCardBuilder(); - * // Finish building the cards ... - * - * // A universal action that shows two static cards. - * var cardsUniversalAction = CardService.newUniversalActionResponseBuilder() - * .displayAddOnCards([ - * cardBuilder1.build(); - * cardBuilder2.build(); - * ]).build(); - */ - export interface UniversalActionResponse { - printJson(): string; - } - - /** - * A builder for the UniversalActionResponse objects. - */ - export interface UniversalActionResponseBuilder { - build(): UniversalActionResponse; - displayAddOnCards(cardObjects: Object[]): UniversalActionResponseBuilder; - setOpenLink(openLink: OpenLink): UniversalActionResponseBuilder; - } - - /** - * Base class for all widgets that can be added to a Card. - */ - export interface Widget { - } - - } -} - -declare var CardService: GoogleAppsScript.Card.CardService; diff --git a/types/google-apps-script/index.d.ts b/types/google-apps-script/index.d.ts index ae463c738b..8e565f334f 100644 --- a/types/google-apps-script/index.d.ts +++ b/types/google-apps-script/index.d.ts @@ -11,28 +11,29 @@ // Google Services (Google APIs) /// -/// -/// /// -/// +/// /// /// /// /// /// -/// +/// /// /// /// /// // Script Services (Other *App / *Service) +/// +/// +/// /// /// -/// /// -/// +/// /// +/// /// /// /// From f41cb80557e9e5bf468d7f75d1cf08635025d7f5 Mon Sep 17 00:00:00 2001 From: SirMcPotato Date: Wed, 26 Dec 2018 23:33:46 +0100 Subject: [PATCH 009/225] Add missing types for module 'ol/interaction/extent' for openlayers@4.6.5 --- types/ol/interaction/extent.d.ts | 3 ++ types/openlayers/index.d.ts | 78 ++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 types/ol/interaction/extent.d.ts diff --git a/types/ol/interaction/extent.d.ts b/types/ol/interaction/extent.d.ts new file mode 100644 index 0000000000..43c69756e3 --- /dev/null +++ b/types/ol/interaction/extent.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Extent; diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index b0356122e4..d7eddc312d 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -5349,6 +5349,76 @@ export namespace interaction { static createRegularPolygon(opt_sides?: number, opt_angle?: number): ol.DrawGeometryFunctionType; } + namespace Extent { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Extent} instances are instances of + * this type. + * + * @param extent the new extent + */ + class Event extends events.Event { + /** + * @classdesc + * Events emitted by {@link ol.interaction.Extent} instances are instances of + * this type. + * + * @param type Type. + * @param feature The feature drawn. + */ + constructor(type: ExtentEventType, extent: ol.Extent); + + /** + * The current extent. + * @api stable + */ + extent: ol.Extent; + } + } + + type ExtentEventType = string; + + /** + * @classdesc + * Interaction for drawing feature geometries. + * + * @fires ol.interaction.DrawEvent + * @param options Options. + * @api stable + */ + class Extent extends Pointer { + /** + * @classdesc + * Interaction for drawing feature geometries. + * + * @fires ol.interaction.DrawEvent + * @param options Options. + * @api stable + */ + constructor(options: olx.interaction.ExtentOptions); + + /** + * @inheritDoc + */ + setMap(map: ol.Map): void; + + /** + * Returns the current drawn extent in the view projection + * + * @return Drawn extent in the view projection. + * @api + */ + getExtent(): ol.Extent; + + /** + * Manually sets the drawn extent, using the view projection. + * + * @param extent Extent + * @api + */ + setExtent(extent: ol.Extent): void; + } + /** * Set of interactions included in maps by default. Specific interactions can be * excluded by setting the appropriate option to false in the constructor @@ -11788,6 +11858,14 @@ export namespace olx { wrapX?: boolean; } + interface ExtentOptions { + extent?: ol.Extent; + boxStyle?: (ol.style.Style | ol.style.Style[] | ol.StyleFunction); + pixelTolerance?: number; + pointerStyle?: (ol.style.Style | ol.style.Style[] | ol.StyleFunction); + wrapX?: boolean; + } + interface TranslateOptions { features?: ol.Collection; layers?: (ol.layer.Layer[] | ((layer: ol.layer.Layer) => boolean)); From 9711d1cc66aab55078608bcb79e68a82b399e7e9 Mon Sep 17 00:00:00 2001 From: SirMcPotato Date: Wed, 26 Dec 2018 23:45:28 +0100 Subject: [PATCH 010/225] Adding tests --- types/openlayers/openlayers-tests.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index 9fb6f0bb3b..e24b4b23f4 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -1032,6 +1032,18 @@ draw = new ol.interaction.Draw({ style: styleFunctionAsArray }); +const itExtent = new ol.interaction.Extent({ + extent: [10, 10, 20 , 20], + boxStyle: style, + pixelTolerance: 10, + pointerStyle: style, + wrapX: true +}); + +itExtent.setMap(map); +itExtent.getExtent(); +itExtent.setExtent([20, 20, 30, 30]); + const dragbox: ol.interaction.DragBox = new ol.interaction.DragBox({ className: stringValue, minArea: 10, From 13347a1effe58de9bcde1ca93c58fa0054424884 Mon Sep 17 00:00:00 2001 From: SirMcPotato Date: Wed, 26 Dec 2018 23:47:09 +0100 Subject: [PATCH 011/225] ol - Register 'interaction/extent.d.ts' into tsconfig --- types/ol/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/ol/tsconfig.json b/types/ol/tsconfig.json index 79e135476e..186bb605e0 100644 --- a/types/ol/tsconfig.json +++ b/types/ol/tsconfig.json @@ -75,6 +75,7 @@ "interaction/dragrotateandzoom.d.ts", "interaction/dragzoom.d.ts", "interaction/draw.d.ts", + "interaction/extent.d.ts", "interaction/interaction.d.ts", "interaction/keyboardpan.d.ts", "interaction/keyboardzoom.d.ts", From a1d768dfe088e4295046d991de3b2ef20a83c27c Mon Sep 17 00:00:00 2001 From: SirMcPotato Date: Thu, 27 Dec 2018 00:09:33 +0100 Subject: [PATCH 012/225] Fix inconsistencies on some annotations --- types/openlayers/index.d.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index d7eddc312d..7c1844663c 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -5380,18 +5380,17 @@ export namespace interaction { /** * @classdesc - * Interaction for drawing feature geometries. + * Allows the user to draw a vector box by clicking and dragging on the map. + * Once drawn, the vector box can be modified by dragging its vertices or edges. + * This interaction is only supported for mouse devices. * - * @fires ol.interaction.DrawEvent + * @fires ol.interaction.Extent.Event * @param options Options. * @api stable */ class Extent extends Pointer { /** - * @classdesc - * Interaction for drawing feature geometries. - * - * @fires ol.interaction.DrawEvent + * @fires ol.interaction.Extent.Event * @param options Options. * @api stable */ From 1ce8992a9a4b3a460372798d9d85a0a7529feb13 Mon Sep 17 00:00:00 2001 From: Slava Yultyyev Date: Wed, 26 Dec 2018 17:45:09 -0800 Subject: [PATCH 013/225] [stripe] Update Accounts type definitions: add `createLoginLink()` method. --- types/stripe/index.d.ts | 21 +++++++++++++++++++++ types/stripe/stripe-tests.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index dcac6a2e19..fa54894200 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -14,6 +14,7 @@ // Troy Zarger // Ifiok Jr. // Simon Schick +// Slava Yultyyev Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -462,6 +463,16 @@ declare namespace Stripe { */ reason: "fraud" | "terms_of_service" | "other" ; } + + interface ILoginLink { + object: "login_link"; + created: number; + + /** + * A single-use login link for an Express account to access their Stripe dashboard. + */ + url: string; + } } namespace applicationFees { @@ -2352,6 +2363,7 @@ declare namespace Stripe { end: number; } } + namespace invoiceItems { interface InvoiceItem extends IResourceObject { /** @@ -5517,6 +5529,14 @@ declare namespace Stripe { */ listExternalAccounts(accId: string, data: accounts.ICardListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; listExternalAccounts(accId: string, data: accounts.ICardListOptions, response?: IResponseFn>): Promise>; + + /** + * Creates a single-use login link for an Express account to access their Stripe dashboard. + * You may only create login links for Express accounts connected to your platform. + * Returns a login link object if the call succeeded. + */ + createLoginLink(accId: string, response?: IResponseFn): Promise; + createLoginLink(accId: string, redirectUrl?: string, response?: IResponseFn): Promise; } class ApplicationFees extends StripeResource { @@ -7518,6 +7538,7 @@ declare namespace Stripe { */ starting_after?: string; } + interface IListOptionsCreated extends IListOptions { /** * A filter on the list based on the object created field. The value can be a string with an integer Unix timestamp, or it can diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index 685f29cd77..49f52b7a38 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -725,6 +725,20 @@ stripe.accounts.retrieve("acct_17wV8KBoqMA9o2xk").then( const payouts_enabled: boolean = accounts.payouts_enabled; } ); +stripe.accounts.createLoginLink("acct_17wV8KBoqMA9o2xk").then( + (loginLink) => { + const object: string = loginLink.object; + const created: number = loginLink.created; + const url: string = loginLink.url; + } +); +stripe.accounts.createLoginLink("acct_17wV8KBoqMA9o2xk", "http://localhost:3000").then( + (loginLink) => { + const object: string = loginLink.object; + const created: number = loginLink.created; + const url: string = loginLink.url; + } +); //#endregion //#region Application Fee Refunds tests From 7e7d467cac23843d46f5511d16534c931cf06dff Mon Sep 17 00:00:00 2001 From: James Lismore Date: Wed, 26 Dec 2018 23:18:19 -0500 Subject: [PATCH 014/225] Add typings for VictoryBoxPlot --- types/victory/index.d.ts | 1628 +++++++++++++++++-------------- types/victory/victory-tests.tsx | 83 +- 2 files changed, 973 insertions(+), 738 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 6178d52bd3..050ea943d7 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -4,6 +4,7 @@ // snerks // Krzysztof Cebula // Vitaliy Polyanskiy +// James Lismore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -1347,759 +1348,912 @@ declare module "victory" { */ export class VictoryBar extends React.Component {} - export interface VictoryChartProps extends VictoryCommonProps { - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The style prop specifies styles for your chart. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} - */ - style?: React.CSSProperties; - } + export interface VictoryBoxPlotStyleInterface + extends VictoryStyleInterface { + max?: React.CSSProperties; + maxLabels?: React.CSSProperties; + min?: React.CSSProperties; + minLabels?: React.CSSProperties; + median?: React.CSSProperties; + medianLabels?: React.CSSProperties; + q1?: React.CSSProperties; + q1Labels?: React.CSSProperties; + q3?: React.CSSProperties; + q3Labels?: React.CSSProperties; + } - /** - * A flexible charting component for React. - * VictoryChart composes other Victory components into reusable charts. - * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, - * and provides a set of sensible defaults. This component works with: - * - VictoryAxis - * - VictoryLine - * - VictoryScatter - * - VictoryBar - */ - export class VictoryChart extends React.Component {} + export interface VictoryBoxPlotProps + extends VictoryCommonProps, + VictoryDatableProps { + /** + * The boxWidth prop specifies how wide each box should be. If the whiskerWidth + * prop is not set, this prop will also determine the width of the whisker crosshair. + */ + boxWidth?: number; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The labelOrientation prop determines where labels are placed relative to their + * corresponding data. If this prop is not set, it will be set to “top” for + * horizontal charts, and “right” for vertical charts. + */ + labelOrientation?: "top" | "bottom" | "left" | "right"; + /** + * When the boolean labels prop is set to true, the values for min, max, median, + * q1, and q3 will be displayed for each box. For more granular label control, use + * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. + */ + labels?: boolean; + /** + * Use the max data accessor prop to define the max value of a box plot. + */ + max?: StringOrNumberOrCallback; + /** + * Use the median data accessor prop to define the median value of a box plot. + */ + median?: StringOrNumberOrCallback; + /** + * Use the min data accessor prop to define the min value of a box plot. + */ + min?: StringOrNumberOrCallback; + /** + * Use the q1 data accessor prop to define the q1 value of a box plot. + */ + q1?: StringOrNumberOrCallback; + /** + * Use the q3 data accessor prop to define the q1 value of a box plot. + */ + q3?: StringOrNumberOrCallback; + /** + * The style prop defines the style of the component. The style prop + * should be given as an object with styles defined for parent, max, + * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, + * q3Labels. Any valid svg styles are supported, but width, height, a + * nd padding should be specified via props as they determine relative + * layout for components in VictoryChart. Functional styles may be + * defined for style properties, and they will be evaluated with each datum. + */ + style?: VictoryBoxPlotStyleInterface; + /** + * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the + * whiskerWidth prop is not set, the width of the whisker crosshair will match + * the width of the box. + */ + whiskerWidth?: number; + } - export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or categorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] + * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for + * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), + * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryGroup, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - } + export class VictoryBoxPlot extends React.Component< + VictoryBoxPlotProps, + any + > {} - export class VictoryGroup extends React.Component {} + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} + */ + style?: React.CSSProperties; + } - export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. - * Since VictoryLine only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a line), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * The interpolation prop determines how data points should be connected - * when plotting a line + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The labels prop defines the labels that will appear above each point. - * This prop should be given as an array or as a function of data. - */ - labels?: string[]|number[]|Function; - /** - * Use the sortKey prop to indicate how data should be sorted. This prop - * is given directly to the lodash sortBy function to be executed on the - * final dataset. - */ - sortKey?: string|string[]|Function; - /** - * The style prop specifies styles for your VictoryLine. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. in addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } + export class VictoryChart extends React.Component {} - /** - * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use line charts and more. - */ - export class VictoryLine extends React.Component {} - - export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + } + + export class VictoryGroup extends React.Component {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The labels prop defines the labels that will appear above each point. + * This prop should be given as an array or as a function of data. + */ + labels?: string[]|number[]|Function; + /** + * Use the sortKey prop to indicate how data should be sorted. This prop + * is given directly to the lodash sortBy function to be executed on the + * final dataset. + */ + sortKey?: string|string[]|Function; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + /** - * The colorScale prop defines a color scale to be applied to each data - * symbol in VictoryLegend. This prop should be given as an array of CSS - * colors, or as a string corresponding to one of the built in color - * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", - * "green", "blue". VictoryLegend will assign a color to each symbol by - * index, unless they are explicitly specified in the data object. - * Colors will repeat when there are more symbols than colors in the - * provided colorScale. + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. */ - colorScale?: ColorScalePropType; - /** - * The style prop defines the style of the VictoryLegend component. - * The style prop should be given as an object with styles defined for data, labels and - * parent. Any valid svg styles are supported, but width, height, and - * padding should be specified via props as they determine relative - * layout for components in VictoryLegend. - */ - style?: VictoryStyleInterface; - /** - * The containerComponent prop takes a component instance which will be - * used to create a container element for standalone legends. The new - * element created from the passed containerComponent will be provided - * with the following props: height, width, children (the legend itself) - * and style. If a containerComponent is not provided, the default - * VictoryContainer component will be used. VictoryContainer supports - * title and desc props, which are intended to add accessibility to - * Victory components. The more descriptive these props are, the more - * accessible your data will be for people using screen readers. These - * props may be set by passing them directly to the supplied component. - * By default, VictoryContainer renders a responsive svg using the - * viewBox attribute. To render a static container, set - * responsive={false} directly on the instance of VictoryContainer - * supplied via the containerComponent prop. VictoryContainer also - * renders a Portal element that may be used in conjunction with - * VictoryPortal to force components to render above other children. - * @default - */ - containerComponent?: React.ReactElement; - /** - * Specify data via the data prop. VictoryLegend expects data as an - * array of objects with name (required), symbol, and labels properties. - * The data prop must be given as an array. - */ - data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; + export class VictoryLine extends React.Component {} + + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The colorScale prop defines a color scale to be applied to each data + * symbol in VictoryLegend. This prop should be given as an array of CSS + * colors, or as a string corresponding to one of the built in color + * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", + * "green", "blue". VictoryLegend will assign a color to each symbol by + * index, unless they are explicitly specified in the data object. + * Colors will repeat when there are more symbols than colors in the + * provided colorScale. + */ + colorScale?: ColorScalePropType; + /** + * The style prop defines the style of the VictoryLegend component. + * The style prop should be given as an object with styles defined for data, labels and + * parent. Any valid svg styles are supported, but width, height, and + * padding should be specified via props as they determine relative + * layout for components in VictoryLegend. + */ + style?: VictoryStyleInterface; + /** + * The containerComponent prop takes a component instance which will be + * used to create a container element for standalone legends. The new + * element created from the passed containerComponent will be provided + * with the following props: height, width, children (the legend itself) + * and style. If a containerComponent is not provided, the default + * VictoryContainer component will be used. VictoryContainer supports + * title and desc props, which are intended to add accessibility to + * Victory components. The more descriptive these props are, the more + * accessible your data will be for people using screen readers. These + * props may be set by passing them directly to the supplied component. + * By default, VictoryContainer renders a responsive svg using the + * viewBox attribute. To render a static container, set + * responsive={false} directly on the instance of VictoryContainer + * supplied via the containerComponent prop. VictoryContainer also + * renders a Portal element that may be used in conjunction with + * VictoryPortal to force components to render above other children. + * @default + */ + containerComponent?: React.ReactElement; + /** + * Specify data via the data prop. VictoryLegend expects data as an + * array of objects with name (required), symbol, and labels properties. + * The data prop must be given as an array. + */ + data?: Array<{ + name?: string; + symbol?: { + fill?: string; + type?: string; + }; + }>; + /** + * The itemsPerRow prop determines how many items to render in each row + * of a horizontal legend, or in each column of a vertical legend. This + * prop should be given as an integer. When this prop is not given, + * legend items will be rendered in a single row or column. + */ + itemsPerRow?: number; + /** + * The dataComponent prop takes a component instance which will be + * responsible for rendering a data element used to associate a symbol + * or color with each data series. The new element created from the + * passed dataComponent will be provided with the following properties + * calculated by VictoryLegend: x, y, size, style, and symbol. Any of + * these props may be overridden by passing in props to the supplied + * component, or modified or ignored within the custom component itself. + * If a dataComponent is not provided, VictoryLegend will use its + * default Point component. + */ + dataComponent?: React.ReactElement; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a tag on web, and a react-native-svg tag on mobile + * @default + */ + groupComponent?: React.ReactElement; + /** + * The gutter prop defines the number of pixels between legend rows or + * columns, depending on orientation. When orientation is horizontal, + * gutters are between columns. When orientation is vertical, gutters + * are the space between rows. + */ + gutter?: number; + /** + * The labelComponent prop takes a component instance which will be used + * to render each legend label. The new element created from the passed + * labelComponent will be supplied with the following properties: x, y, + * style, and text. Any of these props may be overridden by passing in + * props to the supplied component, or modified or ignored within the + * custom component itself. If labelComponent is omitted, a new + * VictoryLabel will be created with the props described above. + */ + labelComponent?: React.ReactElement; + /** + * The orientation prop takes a string that defines whether legend data + * are displayed in a row or column. When orientation is "horizontal", + * legend items will be displayed in a single row. When orientation is + * "vertical", legend items will be displayed in a single column. Line + * and text-wrapping is not currently supported, so "vertical" + * orientation is both the default setting and recommended for + * displaying many series of data. + * @default 'vertical' + */ + orientation?: 'horizontal'|'vertical'; + /** + * The padding prop specifies the amount of padding in pixels between + * the edge of the legend and any rendered child components. This prop + * can be given as a number or as an object with padding specified for + * top, bottom, left and right. As with width and height, the absolute + * padding will depend on whether the component is rendered in a + * responsive container. When a component is nested within + * VictoryLegend, setting padding on the child component will have no + * effect. + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; }; - }>; + /** + * The standalone props specifies whether the component should be + * rendered in an independent element or in a tag. This prop + * defaults to true, and renders an svg. + */ + standalone?: boolean; + /** + * The symbolSpacer prop defines the number of pixels between data + * components and label components. + */ + symbolSpacer?: number; + /** + * The width and height props define the width and height of the legend. + * These props may be given as positive numbers or functions of data. If + * these props are not set, width and height will be determined based on + * an approximate text size calculated from the text and style props + * provided to VictoryLegend. + */ + width?: number; + height?: number; + /** + * The x and y props define the base position of the legend element. + */ + x?: number; + y?: number; + } + /** - * The itemsPerRow prop determines how many items to render in each row - * of a horizontal legend, or in each column of a vertical legend. This - * prop should be given as an integer. When this prop is not given, - * legend items will be rendered in a single row or column. + * VictoryLegend renders a chart legend component. */ - itemsPerRow?: number; + export class VictoryLegend extends React.Component {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + } + /** - * The dataComponent prop takes a component instance which will be - * responsible for rendering a data element used to associate a symbol - * or color with each data series. The new element created from the - * passed dataComponent will be provided with the following properties - * calculated by VictoryLegend: x, y, size, style, and symbol. Any of - * these props may be overridden by passing in props to the supplied - * component, or modified or ignored within the custom component itself. - * If a dataComponent is not provided, VictoryLegend will use its - * default Point component. + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. */ - dataComponent?: React.ReactElement; + export class VictoryScatter extends React.Component {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; + } + + export class VictoryStack extends React.Component {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement; + /** + * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. + * If this prop is not set, the label radius will default to the radius of the pie + label padding. + */ + labelRadius?: number; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; + } + /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a tag on web, and a react-native-svg tag on mobile - * @default + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. */ - groupComponent?: React.ReactElement; - /** - * The gutter prop defines the number of pixels between legend rows or - * columns, depending on orientation. When orientation is horizontal, - * gutters are between columns. When orientation is vertical, gutters - * are the space between rows. - */ - gutter?: number; - /** - * The labelComponent prop takes a component instance which will be used - * to render each legend label. The new element created from the passed - * labelComponent will be supplied with the following properties: x, y, - * style, and text. Any of these props may be overridden by passing in - * props to the supplied component, or modified or ignored within the - * custom component itself. If labelComponent is omitted, a new - * VictoryLabel will be created with the props described above. - */ - labelComponent?: React.ReactElement; - /** - * The orientation prop takes a string that defines whether legend data - * are displayed in a row or column. When orientation is "horizontal", - * legend items will be displayed in a single row. When orientation is - * "vertical", legend items will be displayed in a single column. Line - * and text-wrapping is not currently supported, so "vertical" - * orientation is both the default setting and recommended for - * displaying many series of data. - * @default 'vertical' - */ - orientation?: 'horizontal'|'vertical'; - /** - * The padding prop specifies the amount of padding in pixels between - * the edge of the legend and any rendered child components. This prop - * can be given as a number or as an object with padding specified for - * top, bottom, left and right. As with width and height, the absolute - * padding will depend on whether the component is rendered in a - * responsive container. When a component is nested within - * VictoryLegend, setting padding on the child component will have no - * effect. - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The standalone props specifies whether the component should be - * rendered in an independent element or in a tag. This prop - * defaults to true, and renders an svg. - */ - standalone?: boolean; - /** - * The symbolSpacer prop defines the number of pixels between data - * components and label components. - */ - symbolSpacer?: number; - /** - * The width and height props define the width and height of the legend. - * These props may be given as positive numbers or functions of data. If - * these props are not set, width and height will be determined based on - * an approximate text size calculated from the text and style props - * provided to VictoryLegend. - */ - width?: number; - height?: number; - /** - * The x and y props define the base position of the legend element. - */ - x?: number; - y?: number; + export class VictoryPie extends React.Component {} } - - /** - * VictoryLegend renders a chart legend component. - */ - export class VictoryLegend extends React.Component {} - - type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - - export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The bubbleProperty prop indicates which property of the data object should be used - * to scale data points in a bubble chart - */ - bubbleProperty?: string; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryScatter - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart - */ - maxBubbleSize?: number; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The size prop determines how to scale each data point - */ - size?: number | { (data: any): number }; - /** - * The style prop specifies styles for your VictoryScatter. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - /** - * The symbol prop determines which symbol should be drawn to represent data points. - */ - symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; - } - - /** - * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use scatter plots and more. - */ - export class VictoryScatter extends React.Component {} - - export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or catigorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryStack, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - /** - * The xOffset prop is used for grouping stacks of bars. This prop will be set - * by the VictoryGroup component wrapper, or can be set manually. - */ - xOffset?: number; - } - - export class VictoryStack extends React.Component {} - - export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The colorScale prop is an optional prop that defines the color scale the pie - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryPie will automatically assign - * values from this color scale to the pie slices unless colors are explicitly provided in the - * data object - */ - colorScale?: ColorScalePropType; - /** - * The data prop specifies the data to be plotted, - * where data X-value is the slice label (string or number), - * and Y-value is the corresponding number value represented by the slice - * Data should be in the form of an array of data points. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire, HTML-complete data component which will be used to - * create slices for each datum in the pie chart. The new element created from the passed - * dataComponent will have the property datum set by the pie chart for the point it renders; - * properties style and pathFunction calculated by VictoryPie; an index property set - * corresponding to the location of the datum in the data provided to the pie; events bound to - * the VictoryPie; and the d3 compatible slice object. - * If a dataComponent is not provided, VictoryPie's Slice component will be used. - */ - dataComponent?: React.ReactElement; - /** - * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. - * If this prop is not set, the label radius will default to the radius of the pie + label padding. - */ - labelRadius?: number; - /** - * The overall end angle of the pie in degrees. This prop is used in conjunction with - * startAngle to create a pie that spans only a segment of a circle. - */ - endAngle?: number; - /** - * The event prop takes an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryPie - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: 1, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: 2, - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: 2, - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * When creating a donut chart, this prop determines the number of pixels between - * the center of the chart and the inner edge of a donut. When this prop is set to zero - * a regular pie chart is rendered. - */ - innerRadius?: number; - /** - * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie - */ - cornerRadius?: number; - /** - * The padAngle prop determines the amount of separation between adjacent data slices - * in number of degrees - */ - padAngle?: number; - /** - * The overall start angle of the pie in degrees. This prop is used in conjunction with - * endAngle to create a pie that spans only a segment of a circle. - */ - startAngle?: number; - /** - * The style prop specifies styles for your pie. VictoryPie relies on Radium, - * so valid Radium style objects should work for this prop. Height, width, and - * padding should be specified via the height, width, and padding props. - * @example {data: {stroke: "black"}, label: {fontSize: 10}} - */ - style?: VictoryStyleInterface; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - */ - y?: DataGetterPropType; - } - - /** - * victory-pie draws an SVG pie or donut chart with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryPie extends React.Component {} -} + \ No newline at end of file diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index d7ddd7c33b..09203bf7c4 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -12,7 +12,8 @@ import { VictoryScatter, VictoryPie, VictoryTheme, - VictoryLegend + VictoryLegend, + VictoryBoxPlot } from "victory"; // VictoryAnimation test @@ -317,6 +318,86 @@ test = ( /> ); +// VictoryBoxPlot test +test = ( + ({ y: 0, label: " " }), + after: datum => ({ y: datum.y, label: "NEW" }) + } + }} + boxWidth={10} + domain={[0, 10]} + domainPadding={5} + data={[ + { x: 1, y: [1, 2, 3, 5] }, + { x: 2, y: [3, 2, 8, 10] }, + { x: 3, y: [2, 8, 6, 5] }, + { x: 4, y: [1, 3, 2, 9] } + ]} + events={[ + { + target: "data", + eventKey: 2, + eventHandlers: { + onClick: evt => { + evt.stopPropagation(); + return [ + { + mutation: () => { + return { + style: { fill: "orange", width: 20 } + }; + } + }, + { + target: "labels", + eventKey: 3, + mutation: () => { + return { text: "now click me" }; + } + } + ]; + } + } + }, + { + target: "parent", + eventHandlers: { + onClick: () => { + return [ + { + target: "data", + mutation: () => { + return { + style: { fill: "tomato", width: 10 } + }; + } + } + ]; + } + } + } + ]} + height={500} + labelOrientation="top" + labels={true} + name="BoxPlot" + style={{ + min: { stroke: "tomato" }, + max: { stroke: "orange" }, + q1: { fill: "tomato" }, + q3: { fill: "orange" }, + median: { stroke: "white", strokeWidth: 2 }, + minLabels: { fill: "tomato" }, + maxLabels: { fill: "orange" } + }} + whiskerWidth={5} + /> +); // VictoryChart test test = ( From 9334c854fb65e74930fa7fcdb8cf68629ec28708 Mon Sep 17 00:00:00 2001 From: "Ryosuke.I" Date: Thu, 27 Dec 2018 15:18:03 +0900 Subject: [PATCH 015/225] add definition of highlightLines --- types/ace/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index cd20b57f05..2588539c0c 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -549,6 +549,16 @@ declare namespace AceAjax { getFoldsInRange(range: Range): any; highlight(text: string): void; + + + /** + * Highlight lines from `startRow` to `EndRow`. + * @param startRow Define the start line of the highlight + * @param endRow Define the end line of the highlight + * @param clazz Set the CSS class for the marker + * @param inFront Set to `true` to establish a front marker + **/ + highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range; /** * Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`. From 094fd3d21ed4780f1a9e747657675e6de3c534ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?I=C3=B1igo?= Date: Thu, 27 Dec 2018 13:36:18 +0100 Subject: [PATCH 016/225] Add googleCallbackName property to PropTypes --- types/react-places-autocomplete/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..e0fb483eac 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -6,8 +6,7 @@ // TypeScript Version: 2.8 // /// - -import * as React from "react"; +import * as React from 'react'; export interface formattedSuggestionType { mainText: string; @@ -52,6 +51,7 @@ export interface PropTypes { debounce?: number; highlightFirstSuggestion?: boolean; + googleCallbackName?: string; renderFooter?: () => React.ReactNode; shouldFetchSuggestions?: (value: string) => boolean; } From b610c8bd991687572743dd70ed13910dcebff336 Mon Sep 17 00:00:00 2001 From: David Gomes Date: Thu, 27 Dec 2018 14:23:01 +0000 Subject: [PATCH 017/225] Fixes type definition of Form Section in Redux Form. --- types/redux-form/lib/FormSection.d.ts | 8 +++----- types/redux-form/redux-form-tests.tsx | 11 +++-------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/types/redux-form/lib/FormSection.d.ts b/types/redux-form/lib/FormSection.d.ts index fa7f725f21..bed9ba765b 100644 --- a/types/redux-form/lib/FormSection.d.ts +++ b/types/redux-form/lib/FormSection.d.ts @@ -1,12 +1,10 @@ import { Component, ComponentType } from "react"; -export type GenericFormSection

= Component

>; - -export interface FormSectionProps

{ +export interface FormSectionProps

{ name: string; - component?: string | ComponentType

; + component?: ComponentType

; } -export declare class FormSection extends Component {} +export declare class FormSection

extends Component & P> {} export default FormSection; diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 70fb1f4e13..df27aa41fe 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -7,7 +7,6 @@ import { FormName, GenericForm, FormSection, - GenericFormSection, formValues, formValueSelector, Field, @@ -101,8 +100,8 @@ const ItemListObj = formValues({ fooBar : "foo" })( interface MyFormSectionProps { foo: string; } -const MyFormSection: React.StatelessComponent = ({ children }) => null; -const FormSectionCustom = FormSection as new () => GenericFormSection; + +const MyFormSection: React.StatelessComponent = ({ children, foo }) => null; /* Custom Field */ @@ -253,11 +252,7 @@ const Test = reduxForm({ return (

- + name="my-section" component={MyFormSection} foo="hello" />; Date: Thu, 27 Dec 2018 14:36:43 +0000 Subject: [PATCH 018/225] Fix indentation in test. --- types/redux-form/redux-form-tests.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index df27aa41fe..5b00434022 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -252,7 +252,11 @@ const Test = reduxForm({ return (
- name="my-section" component={MyFormSection} foo="hello" />; + + name="my-section" + component={MyFormSection} + foo="hello" + /> Date: Thu, 27 Dec 2018 15:59:39 +0100 Subject: [PATCH 019/225] Commented react-places-autocomplete version --- types/react-places-autocomplete/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index e0fb483eac..25ae14e33a 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-places-autocomplete 6.1 +// Type definitions for react-places-autocomplete 7.2 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov From 09babd8bb368eefbde45506f1d56a91f5eabda16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?I=C3=B1igo?= Date: Thu, 27 Dec 2018 16:20:49 +0100 Subject: [PATCH 020/225] Included googleCalbackName on the test --- .../react-places-autocomplete-tests.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..2a567df8a4 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -1,5 +1,7 @@ import * as React from 'react'; -import PlacesAutocomplete, { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete'; +import PlacesAutocomplete, { + geocodeByAddress, geocodeByPlaceId, getLatLng +} from 'react-places-autocomplete'; class Test extends React.Component { state = { @@ -45,7 +47,7 @@ class Test extends React.Component { return (
- + ); } From 94e24d5c7422b933839392acae0a2fdfacdedd32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?I=C3=B1igo?= Date: Thu, 27 Dec 2018 17:30:42 +0100 Subject: [PATCH 021/225] Resolve conflict --- types/react-places-autocomplete/index.d.ts | 11 ++++++----- .../react-places-autocomplete-tests.tsx | 7 +------ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 25ae14e33a..b2f0c661cd 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov +// Nokky Goren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 // @@ -14,13 +15,10 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -40,7 +38,7 @@ export interface PropTypes { autocompleteItem?: React.CSSProperties; autocompleteItemActive?: React.CSSProperties; }; - options?: { + searchOptions?: { bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral; componentRestrictions?: google.maps.GeocoderComponentRestrictions; location?: google.maps.LatLng | google.maps.LatLngLiteral; @@ -48,6 +46,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value?: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 2a567df8a4..331d453bf0 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -40,14 +40,9 @@ class Test extends React.Component { onChange = (address: string) => this.setState({ address }); render() { - const inputProps = { - value: this.state.address, - onChange: this.onChange, - }; - return (
- + ); } From 0d20a346cf9605b84c521d86cd395c8901857dc4 Mon Sep 17 00:00:00 2001 From: Andrew Kittredge Date: Fri, 21 Dec 2018 12:09:21 -0500 Subject: [PATCH 022/225] [ui-grid] Fix signature of getVisibleRows I don't think getVisibleRows takes any arguments. The definition of getVisibleRows from line 1800 of https://github.com/angular-ui/ui-grid/blob/47c12394b0e8adf56a78e4e8b6a6f496554f910b/packages/core/src/js/factories/Grid.js is- Grid.prototype.getVisibleRows = function getVisibleRows() { return this.renderContainers.body.visibleRowCache; }; --- types/ui-grid/index.d.ts | 3 +-- types/ui-grid/ui-grid-tests.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/types/ui-grid/index.d.ts b/types/ui-grid/index.d.ts index 9334e91669..8056b4cc07 100644 --- a/types/ui-grid/index.d.ts +++ b/types/ui-grid/index.d.ts @@ -927,10 +927,9 @@ declare namespace uiGrid { clearRowInvisible(rowEntity: TEntity): void; /** * Returns all visible rows - * @param {IGridInstance} grid the grid you want to get visible rows from * @returns {Array} an array of gridRow */ - getVisibleRows(grid: IGridInstanceOf): Array>; + getVisibleRows(): Array>; /** * Trigger a grid resize, normally this would be picked * up by a watch on window size, but in some circumstances it is necessary diff --git a/types/ui-grid/ui-grid-tests.ts b/types/ui-grid/ui-grid-tests.ts index 1e424985fb..027619b3d4 100644 --- a/types/ui-grid/ui-grid-tests.ts +++ b/types/ui-grid/ui-grid-tests.ts @@ -117,7 +117,7 @@ var uiGridConstants: uiGrid.IUiGridConstants; gridApi.core.clearAllFilters(true); gridApi.core.addToGridMenu(gridInstance, [menuItem]); -gridApi.core.getVisibleRows(gridInstance); +gridApi.core.getVisibleRows(); gridApi.core.handleWindowResize(); gridApi.core.queueGridRefresh(); gridApi.core.queueRefresh(); From 5d32c39e0ae260e75a691a584c08cd1213182497 Mon Sep 17 00:00:00 2001 From: Slava Yultyyev Date: Thu, 27 Dec 2018 16:15:52 -0800 Subject: [PATCH 023/225] [stripe] Update Transfers type definitions --- types/stripe/index.d.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index fa54894200..3f0fe418f4 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4000,16 +4000,9 @@ declare namespace Stripe { destination?: string; /** - * Only return transfers for the recipient specified by this - * recipient ID. + * Only return transfers with the specified transfer group. */ - recipient?: string; - - /** - * Only return transfers that have the given status: - * pending, paid, failed, in_transit, or canceled. - */ - status: Statuses; + transfer_group?: string | null; } type SourceTypes = "alipay_account" | "bank_account" | "bitcoin_receiver" | "card"; From 64e58df5b886ebc9d084bced36830d348d25dbfe Mon Sep 17 00:00:00 2001 From: Sara Nordmyr da Cunha Date: Thu, 27 Dec 2018 17:17:46 +0100 Subject: [PATCH 024/225] Update types in vast-client to version 2.1 --- types/vast-client/index.d.ts | 430 +++++++++++++++---------- types/vast-client/tsconfig.json | 2 +- types/vast-client/tslint.json | 11 +- types/vast-client/vast-client-tests.ts | 144 ++++++--- 4 files changed, 368 insertions(+), 219 deletions(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index 4ab079a431..b864a685c9 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -1,79 +1,94 @@ -// Type definitions for vast-client 1.7 +// Type definitions for vast-client 2.1 // Project: https://github.com/dailymotion/vast-client-js#readme -// Definitions by: John G. Gainfort, Jr. +// Definitions by: John G. Gainfort Jr. , Sara Nordmyr da Cunha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 -export const client: VastClient; -export const parser: VastParser; +import { EventEmitter } from 'events'; -export class tracker { +export class VASTTracker extends EventEmitter { /** * The VAST tracker constructor will process the tracking URLs of the selected ad/creative and returns an instance of VASTTracker. - * You can create an instance with new DMVAST.tracker( ad , creative ). - * - * Object ad – Reference to the element of the selected mediaFile - * Object creative – Reference to the element of the selected mediaFile - * Object variationd - An optional reference to the selected / element for non-linear ads */ - constructor(ad: VastAd, creative: VastCreativeLinear, companion?: VastCreativeCompanion); + constructor( + /** + * An optional instance of VASTClient that can be updated by the tracker. + */ + client: VASTClient | null, + /** + * The ad of the selected mediaFile to track + */ + ad: VastAd, + /** + * The creative of the selected mediaFile to track + */ + creative: VastCreativeLinear, + /** + * An optional variation of the creative, for Companion and NonLinear Ads + */ + variation?: VastCreativeCompanion | VastCreativeNonLinear, + ); /** - * Add a listener function for the specified event. - * - * eventName – Name of the event to attach the listener to. See events below for all details. - * listener – Method to be called when the event is emitted. + * Sets the duration of the ad and updates the quartiles based on that. */ - on(eventName: string, listener: (data?: any) => void): void; + setDuration(duration: number): void; /** - * Remove a listener function for the specified event. - * - * eventName – Name of the event. - * listener – Method to remove. Will remove all listeners for the given event if no specific callback is passed. + * Update the current time value. + * This is required for tracking time related events such as start, firstQuartile, midpoint, thirdQuartile or rewind. */ - off(eventName: string, listener?: () => void): void; - /** - * Remove all listener functions for the specified event. - * - * eventName – Name of the event. - */ - removeAllListeners(eventName: string): void; - /** - * Update the current time value. This is required for tracking time related events such as start, firstQuartile, midpoint, thirdQuartile or rewind. - * - * progess – Current playback time in seconds. - */ - setProgress(progress: number): void; + setProgress( + /** + * Current playback time in seconds. + */ + progress: number + ): void; /** * Update the mute state and call the mute/unmute tracking URLs. Emit a mute or unmute event. - * - * muted – Indicate if the video is muted or not. */ - setMuted(muted: boolean): void; + setMuted( + /** + * Indicate if the video is muted or not. + */ + muted: boolean + ): void; /** * Update the pause state and call the resume/pause tracking URLs. Emit a resume or pause event. - * - * paused – Indicate if the video is paused or not. */ - setPaused(paused: boolean): void; + setPaused( + /** + * Indicate if the video is paused or not. + */ + paused: boolean + ): void; /** * Update the fullscreen state and call the fullscreen tracking URLs. Emit a fullscreen or exitFullscreen event. - * - * fullscreen – Indicate the fullscreen mode. */ - setFullscreen(fullscreen: boolean): void; + setFullscreen( + /** + * Indicate the fullscreen mode. + */ + fullscreen: boolean + ): void; /** * Update the expand state and call the expand/collapse tracking URLs. Emit a expand or collapse event - * - * Boolean expanded – Indicate if the video is expanded or no */ - setExpand(expanded: boolean): void; + setExpand( + /** + * Indicate if the video is expanded or no + */ + expanded: boolean, + ): void; /** * Must be called if you want to overwrite the Skipoffset value. This will init the skip countdown duration. * Then, every time you call setProgress(), it will decrease the countdown and emit a skip-countdown event with the remaining time. * Do not call this method if you want to keep the original Skipoffset value. - * - * duration – The time in seconds until the skip button is displayed. */ - setSkipDelay(duration: number): void; + setSkipDelay( + /** + * The time in seconds until the skip button is displayed. + */ + duration: number + ): void; /** * Report the impression URI. Can only be called once. Will report the following URI: * @@ -82,19 +97,24 @@ export class tracker { * * Once done, a creativeView event is emitted. */ - load(): void; + trackImpression(): void; /** * Send a request to the URI provided by the VAST element. If an [ERRORCODE] macro is included, it will be substitute with code. - * - * code – Replaces [ERRORCODE] macro. [ERRORCODE] values are liste in the VAST specification. */ - errorWithCode(code: string): void; + errorWithCode( + /** + * Replaces [ERRORCODE] macro. [ERRORCODE] values are liste in the VAST specification. + */ + errorCode: string + ): void; /** - * Must be called when the user watched the linear creative until its end. Call the complete tracking URLs. Emit a complete events when done. + * Must be called when the user watched the linear creative until its end. Call the complete tracking URLs. + * Emit a complete events when done. */ complete(): void; /** - * Must be called when the player or the window is closed during the ad. Call the closeLinear (in VAST 3.0) and close tracking URLs. Emit a closeLinear or a close event when done. + * Must be called when the player or the window is closed during the ad. Call the closeLinear (in VAST 3.0) and close tracking URLs. + * Emit a closeLinear or a close event when done. */ close(): void; /** @@ -102,43 +122,68 @@ export class tracker { */ skip(): void; /** - * Must be called when the user clicks on the creative. Call the tracking URLs. Emit a clickthrough event with the resolved clickThrough URL when done. + * Must be called when the user clicks on the creative. Call the tracking URLs. + * Emit a clickthrough event with the resolved clickThrough URL when done. */ click(): void; } -export interface VastClient { - /** - * Used for ignoring the first n calls. Automatically reset 1 hour after the 1st ignored call. Free Lunch capping is disable if sets to 0. - * Default: 0 - */ +export class VASTClient { + constructor( + /** + * Used for ignoring the first n calls. Automatically reset 1 hour after the 1st ignored call. Free Lunch capping is disable if sets to 0. + * Default: 0 + */ + cappingFreeLunch?: number, + /** + * Used for ignoring calls that happen n ms after the previous call. Minimum time interval is disabled if sets to 0. + * Default: 0 + */ + cappingMinimumTimeInterval?: number, + /** + * Optional custom storage to be used instead of the default one + */ + customStorage?: VASTClientCustomStorage, + ); cappingFreeLunch: number; - /** - * Used for ignoring calls that happen n ms after the previous call. Minimum time interval is disabled if sets to 0. - * Default: 0 - */ cappingMinimumTimeInterval: number; + storage: VASTClientCustomStorage | Storage; /** * Fetch a URL and parse the response into a valid VAST object. * - * String url – Contains the URL for fetching the VAST XML document. - * Object options – An optional set of key/value to configure the Ajax request: - * String response – A VAST XML document. When response is provided, no Ajax request is made and thus the url parameter is ignored - * Object urlhandler – A URL handler module, used to fetch the VAST document instead of the default ones. - * Boolean withCredentials – A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers. - * Number wrapperLimit – A number of available Wrapper responses that can be received with no InLine response. - * Function done – Method to be called once the VAST document is parsed. The VAST JS object is passed as the 1st parameter. If null, an error is provided as a 2nd parameter. + * @param url Contains the URL for fetching the VAST XML document. + * @param options An optional set of key/value to configure the Ajax request */ - get(url: string, done: (response: VastResponse, error: Error) => void): void; - get(url: string, options: VastRequestOptions, done: (response: VastResponse, error: Error) => void): void; + get(url: string, options?: VastRequestOptions): Promise; + /** + * Returns a boolean indicating if there are more ads to resolve for the current parsing. + */ + hasRemainingAds(): boolean; + /** + * Resolves the next group of ads. If all is true resolves all the remaining ads. + */ + getNextAds(all?: boolean): Promise; + /** + * Returns the instance of VASTParser used by the client to parse the VAST. + * Use it to directly call a method provided by the VASTParser class. + */ + getParser(): VASTParser; } -export interface VastParser { +export class VASTParser extends EventEmitter { + /** + * util method for handling urls, it is used to make the requests. + */ + urlHandler: VASTClientUrlHandler; /** * Add the replace function at the end of the URLTemplateFilters array. * All functions in URLTemplateFilters will be called with the VAST URL as parameter before fetching the VAST URL document. */ addURLTemplateFilter(cb: (vastUrl: string) => string): void; + /** + * Removes the last element of the url templates filters array. + */ + removeURLTemplateFilter(): void; /** * Reset URLTemplateFilters to empty, previous replace function set with addURLTemplateFilter() are no longer called. */ @@ -148,70 +193,102 @@ export interface VastParser { */ countURLTemplateFilters(): number; /** - * Parse an VAST xml, resolve any wrappers and execute callback function done - * - * String XMLDocument – A VAST XML document. - * Object options – An optional set of key/value to configure the Ajax request: - * Object urlhandler – A URL handler module, used to fetch VASTAdTagURI URL. If defined, will be used instead of the default ones. - * Boolean withCredentials – A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers. - * Number wrapperLimit – A number of available Wrapper responses that can be received with no InLine response. - * Function done – Method to be called once the VAST document is parsed. When at least 1 valid has been found, the 1st parameter will be an array of VASTAd instances. - * Hoverwise, in case of no ads, it will be null, and an error as a 2nd parameter is provided. + * Tracks the error provided in the errorCode parameter and emits a VAST-error event for the given error. */ - load(xml: string, done: (response: VastResponse, error: Error) => void): void; - load(xml: string, options: VastRequestOptions, done: (response: VastResponse, error: Error) => void): void; + trackVastError( + /** + * An Array of url templates to use to make the tracking call + */ + urlTemplates: string[], + errorCode: Pick, + ...data: Array>>, + ): void; /** - * Add the listener function for the event named eventName. eventName value can be : - * - * String VAST-error – emitted when the parser encountered a VAST error (ie: no ads, warapper timeout...). - * The VAST error code is passed to the listener function as a parameter. + * Fetches a VAST document for the given url. + * Returns a Promise which resolves with the fetched xml or rejects with an error, according to the result of the request. */ - on(eventName: string, listener: (error: VastError) => void): void; + fetchVAST( + /** + * The url to request the VAST document. + */ + url: string, + /** + * how many times the current url has been wrapped + */ + wrapperDepth?: number, + /** + * url of original wrapper + */ + originalUrl?: string + ): Promise; /** - * Add a one time listener function for the event named eventName. + * Fetches and parses a VAST for the given url. + * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. */ - once(eventName: string, listener: (data?: any) => void): void; + getAndParseVAST( + /** + * The url to request the VAST document. + */ + url: string, + /** + * An optional Object of parameters to be used in the parsing process. + */ + options?: VastRequestOptions, + ): Promise; /** - * Fetch a URL and parse the response into a valid VAST object. - * - * String url – The VAST XML document URL to fetch. - * Object options – An optional set of key/value to configure the Ajax request: - * Object urlhandler – A URL handler module, used to fetch the VAST document instead of the default ones. - * Boolean withCredentials – A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers. - * Number wrapperLimit – A number of available Wrapper responses that can be received with no InLine response. - * Function done – Method to be called once the VAST document is parsed. When at least 1 valid has been found, the 1st parameter will be an array of VASTAd instances. - * Hoverwise, in case of no ads, it will be null, and an error as a 2nd parameter is provided. + * Parses the given xml Object into a VASTResponse. + * Returns a Promise which either resolves with the fully parsed VASTResponse or rejects with an Error. */ - parse(url: string, done: (response: VastResponse, error: Error) => void): void; - parse(url: string, options: VastRequestOptions, done: (response: VastResponse, error: Error) => void): void; - /** - * Remove the specified listener for the event named eventName. - */ - off(eventName: string, listener: (error: VastError) => void): void; - /** - * Remove replace function from URLTemplateFilters array. - * Replace function won't be called on the next VAST URL encountred by the parser. - */ - removeURLTemplateFilter(cb: (vastUrl: string) => string): void; + parseVAST( + /** + * A VAST XML document + */ + vastXml: Document, + /** + * An optional Object of parameters to be used in the parsing process. + */ + options?: VastRequestOptions, + ): Promise; +} + +export interface VASTClientCustomStorage { + getItem(key: string): string | null; + setItem(key: string, val: string): void; + [key: string]: any | (() => any); +} + +export function UrlHandlerCbType(err: null, xml: XMLDocument): void; +export function UrlHandlerCbType(err: Error): void; + +export interface VASTClientUrlHandler { + get( + url: string, + options: { timeout: number, withCredentials: boolean }, + cb: typeof UrlHandlerCbType, + ): void; } export interface VastRequestOptions { /** - * A VAST XML document. When response is provided, no Ajax request is made and thus the url parameter is ignored. + * A custom timeout for the requests (default 0) */ - response?: string; + timeout?: number; /** - * A URL handler module, used to fetch the VAST document instead of the default ones. - */ - urlhandler?: any; - /** - * A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers. + * A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers (default false) */ withCredentials?: boolean; /** - * A number of available Wrapper responses that can be received with no InLine response. + * A number of Wrapper responses that can be received with no InLine response (default 0) */ wrapperLimit?: number; + /** + * Custom urlhandler to be used instead of the default ones urlhandlers + */ + urlHandler?: VASTClientUrlHandler; + /** + * Allows you to parse all the ads contained in the VAST or to parse them ad by ad or adPod by adPod (default true) + */ + resolveAll?: boolean; } export interface VastResponse { @@ -228,25 +305,28 @@ export interface VastError { * VAST error 302: Wrapper limit reached. * VAST error 303: No VAST response after one or more Wrappers. */ - ERRORCODE: string; + ERRORCODE: string | number; + ERRORMESSAGE?: string; + extensions?: VastAdExtension[]; + system?: VastSystem | string | null; } export interface VastCreative { - id: string; - adId: string; + id: string | null; + adId: string | null; trackingEvents: VastTrackingEvents; - apiFramework: any; - sequence: any; + apiFramework: string | null; + sequence: string | number | null; type: string; } export interface VastCreativeLinear extends VastCreative { - adParameters: any; + adParameters: string | null; duration: number; - icons: string[]; + icons: VastIcon[]; mediaFiles: VastMediaFile[]; - skipDelay: boolean; - videoClickThroughURLTemplate: string; + skipDelay: number | null; + videoClickThroughURLTemplate: string | null; videoClickTrackingURLTemplates: string[]; videoCustomClickURLTempaltes: string[]; } @@ -260,19 +340,18 @@ export interface VastCreativeCompanion extends VastCreative { } export interface VastAd { - advertiser: any; + advertiser: string | null; creatives: VastCreative[]; - description: string; + description: string | null; errorURLTemplates: string[]; extensions: VastAdExtension[]; - id: string; + id: string | null; impressionURLTemplates: string[]; - pricing: any; - sequence: string; - survey: any; - system: VastSystem; - title: string; - hasHLS: boolean; + pricing: string | null; + sequence: string | null; + survey: string | null; + system: VastSystem | string | null; + title: string | null; } export interface VastAdExtension { @@ -282,67 +361,71 @@ export interface VastAdExtension { export interface VastAdAttributes { type: string; + fallback_index: string | null; } export interface VastAdExtensionChild { attributes: VastAdChildAttributes; - name: string; - value: string; + name: string | undefined; + value: string | number; } export interface VastAdChildAttributes { - name: string; + [key: string]: any; } export interface VastNonLinearAd { nonLinearClickTrackingURLTemplates: string[]; - nonLinearClickThroughURLTemplate: string; - adParameters: string; - type: string; - iframeResource: string; - htmlResource: string; - id: string; + nonLinearClickThroughURLTemplate: string | null; + adParameters: string | null; + type: string | null; + iframeResource: string | null; + htmlResource: string | null; + id: string | null; width: string; height: string; expandedWidth: string; expandedHeight: string; - scalablle: boolean; + scalable: boolean; maintainAspectRatio: boolean; minSuggestedDuration: number; - apiFramework: any; + apiFramework: string; + staticResource: string | null; } export interface VastCompanionAd { - companionClickThroughURLTemplate: string; - companionClickTrackingURLTemplate: string; + companionClickThroughURLTemplate: string | null; + companionClickTrackingURLTemplate: string | null | undefined; companionClickTrackingURLTemplates: string[]; height: string; - htmlResource: string; - id: string; - iframeResource: string; - staticResource: string; + htmlResource: string | null; + id: string | null; + iframeResource: string | null; + staticResource: string | null; trackingEvents: VastCompanionTrackingEvents; - type: string; + type: string | null; width: string; + altText: string | null; } export interface VastCompanionTrackingEvents { creativeView: string[]; + [key: string]: string[]; } export interface VastMediaFile { - apiFramework: any; + apiFramework: string | null; bitrate: number; - codec: string; + codec: string | null; deliveryType: string; - fileURL: string; + fileURL: string | null; height: number; - id: string; - maintainAspectRatio: boolean; + id: string | null; + maintainAspectRatio: boolean | null; maxBitrate: number; - mimeType: string; + mimeType: string | null; minBitrate: number; - scalable: any; + scalable: boolean | null; width: number; } @@ -351,9 +434,28 @@ export interface VastTrackingEvents { firstQuartile: string[]; midpoint: string[]; thirdQuartile: string[]; + [key: string]: string[]; } export interface VastSystem { value: string; - version: string; + version: string | null; +} + +export interface VastIcon { + program: string | null; + height: number; + width: number; + xPosition: number; + yPosition: number; + apiFramework: string | null; + offset: string | null; + duration: number; + type: string | null; + staticResource: string | null; + htmlResource: string | null; + iframeResource: string | null; + iconClickThroughURLTemplate: string | null; + iconClickTrackingURLTemplates: string[]; + iconViewTrackingURLTemplate: string | null; } diff --git a/types/vast-client/tsconfig.json b/types/vast-client/tsconfig.json index 106b26913c..f9035f9bb5 100644 --- a/types/vast-client/tsconfig.json +++ b/types/vast-client/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "vast-client-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/vast-client/tslint.json b/types/vast-client/tslint.json index 6b8896fa25..20cdc7545e 100644 --- a/types/vast-client/tslint.json +++ b/types/vast-client/tslint.json @@ -1,8 +1,7 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-angle-bracket-type-assertion": false, - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json", + "rules": { + "no-object-literal-type-assertion": false, + "no-any-union": false + } } diff --git a/types/vast-client/vast-client-tests.ts b/types/vast-client/vast-client-tests.ts index aadf2c8370..53ecf850fe 100644 --- a/types/vast-client/vast-client-tests.ts +++ b/types/vast-client/vast-client-tests.ts @@ -1,85 +1,133 @@ -import * as DMVAST from 'vast-client'; +import { + VASTClient, + VASTParser, + VASTTracker, + VastResponse, + VastAd, + VastCreativeLinear, + VASTClientCustomStorage, + VASTClientUrlHandler, + VastCreativeCompanion, +} from 'vast-client'; const VASTUrl = 'http://example.dailymotion.com/vast.xml'; -function cb(response: DMVAST.VastResponse, error: Error): void { - if (error) return; +const VASTXml = new DOMParser().parseFromString("", "text/xml"); + +function cbSuccess(response: VastResponse): void { // process the VAST response - const ads: DMVAST.VastAd[] = response.ads; + const ads: VastAd[] = response.ads; const linearCreative = response.ads[0].creatives.filter(creative => { return creative.type === 'linear'; }); if (linearCreative && linearCreative.length > 0) { - const creative = linearCreative[0] as DMVAST.VastCreativeLinear; + const creative = linearCreative[0] as VastCreativeLinear; const mediaFiles = creative.mediaFiles; } } +function cbError(error: Error): void { + // handle error + return; +} + // CLIENT -// Ignore the first 2 calls -DMVAST.client.cappingFreeLunch = 2; +const customStorage: VASTClientCustomStorage = { + data: {}, + getItem(key) { + return this.data[key]; + }, + setItem(key, value) { + this.data[key] = value; + }, +}; -// Those following DMVAST.client.get calls won't be done -DMVAST.client.get(VASTUrl, cb); -DMVAST.client.get(VASTUrl, cb); +const client = new VASTClient(5, 60000, customStorage); + +// Ignore the first 2 calls +client.cappingFreeLunch = 2; + +// Those following client.get calls won't be done +client.get(VASTUrl).then(cbSuccess).catch(cbError); +client.get(VASTUrl).then(cbSuccess).catch(cbError); // VASTUrl will be called -DMVAST.client.get(VASTUrl, cb); +client.get(VASTUrl).then(cbSuccess).catch(cbError); // Ignore any call made 5 minutes or less after one. -DMVAST.client.cappingMinimumTimeInterval = 5 * 60 * 1000; - -// Work -DMVAST.client.get(VASTUrl, cb); +client.cappingMinimumTimeInterval = 5 * 60 * 1000; // ... // 2 minutes later // Ignored -DMVAST.client.get(VASTUrl, cb); +client.get(VASTUrl).then(cbSuccess).catch(cbError); // ... // 4 minutes later // Work -DMVAST.client.get(VASTUrl, cb); +client.get(VASTUrl).then(cbSuccess).catch(cbError); + +// with options +const urlHandler: VASTClientUrlHandler = { + get: (url, options, cb) => { + // get xml + cb(null, VASTXml); + // or call with error + cb(new Error("no vast")); + }, +}; +client.get(VASTUrl, { urlHandler }).then(cbSuccess).catch(cbError); + +if (client.hasRemainingAds()) { + client.getNextAds() + .then(res => { + // Do something with the next Ads + }) + .catch(err => { + // Deal with the error + }); +} // PARSER -DMVAST.parser.addURLTemplateFilter((vastUrl: string): string => { - return vastUrl.replace('[DOMAIN]', 'mywebsite.com'); -}); - -const count = DMVAST.parser.countURLTemplateFilters(); - -DMVAST.parser.clearUrlTemplateFilters(); - -const xml = 'some xml'; -const options = { - withCredentials: true, - wrapperLimit: 5 -}; - -DMVAST.parser.load(xml, options, cb); - -const url = 'http://example.dailymotion.com/vast.xml'; - -DMVAST.parser.parse(url, options, cb); +const parser = new VASTParser(); const replaceDomain = (url: string): string => { return url.replace('[DOMAIN]', 'mywebsite.com'); }; -DMVAST.parser.addURLTemplateFilter(replaceDomain); -DMVAST.parser.removeURLTemplateFilter(replaceDomain); +parser.addURLTemplateFilter(replaceDomain); + +const count = parser.countURLTemplateFilters(); + +parser.clearUrlTemplateFilters(); + +parser.trackVastError(['http://errorUrlTemplate.com/'], { ERRORCODE: 301 }, { ERRORMESSAGE: "error message" }); + +parser.fetchVAST(VASTUrl).then(xml => { + // do something with xml document + return xml.documentElement.nodeName === 'VAST'; +}).catch(error => { + // handle error +}); + +const options = { + withCredentials: true, + wrapperLimit: 5 +}; +parser.getAndParseVAST(VASTUrl, options).then(cbSuccess).catch(cbError); + +parser.parseVAST(VASTXml).then(cbSuccess).catch(cbError); // TRACKER // Create a VAST Tracker instance for a linear ad -const vastTracker = new DMVAST.tracker({} as DMVAST.VastAd, {} as DMVAST.VastCreativeLinear); +const vastTracker = new VASTTracker(client, {} as VastAd, {} as VastCreativeLinear); // Create a VAST Tracker instance for a companion ad -// const vastTracker = new DMVAST.tracker({} as DMVAST.VastAd, {} as DMVAST.VastCreativeLinear, {} as DMVAST.VastCreativeCompanion); +const vastTrackerCompanion = new VASTTracker(client, {} as VastAd, {} as VastCreativeLinear, {} as VastCreativeCompanion); const onSkip = () => { console.log('Ad unit skipped'); @@ -88,13 +136,13 @@ const onSkip = () => { // Log a message when event 'skip' is emitted vastTracker.on('skip', onSkip); // Stop logging message -vastTracker.off('skip', onSkip); +// vastTracker.off('skip', onSkip); -const player: HTMLVideoElement = document.getElementById('playerId'); +const player = document.getElementById('playerId') as HTMLVideoElement; // Bind a timeupdate listener to the player player.addEventListener('timeupdate', (e) => { - vastTracker.setProgress(( e.target).currentTime); + vastTracker.setProgress((e.target as HTMLVideoElement).currentTime); }); vastTracker.on('firstQuartile', () => { @@ -103,7 +151,7 @@ vastTracker.on('firstQuartile', () => { // Bind a volumechange listener to the player player.addEventListener('volumechange', (e) => { - vastTracker.setMuted(( e.target).muted); + vastTracker.setMuted((e.target as HTMLVideoElement).muted); }); vastTracker.on('mute', () => { @@ -129,7 +177,7 @@ vastTracker.on('pause', () => { // Bind fullscreenchange listener to the player // Note that the fullscreen API is still vendor-prefixed in browsers player.addEventListener('fullscreenchange', (e) => { - const isFullscreen = !!document.fullscreenElement; + const isFullscreen = true; vastTracker.setFullscreen(isFullscreen); }); @@ -144,7 +192,7 @@ vastTracker.on('exitFullscreen', () => { // Sample function for a button that increase/decrease player size let playerExpanded = false; -const expandButton = document.getElementById('buttonId'); +const expandButton = document.getElementById('buttonId') as HTMLButtonElement; function increasePlayerSize(): void { // do nothing @@ -177,7 +225,7 @@ vastTracker.setSkipDelay(5); // Bind canplay listener to the player player.addEventListener('canplay', () => { - vastTracker.load(); + vastTracker.trackImpression(); }); vastTracker.on('creativeView', () => { @@ -216,7 +264,7 @@ vastTracker.on('close', () => { }); // Bind click listener to the skip button -const skipButton = document.getElementById('buttonId'); +const skipButton = document.getElementById('buttonId') as HTMLButtonElement; skipButton.addEventListener('click', () => { vastTracker.skip(); From 662d8d09403c3784c2a6fbad1cee1a4d497072ec Mon Sep 17 00:00:00 2001 From: Sara Nordmyr da Cunha Date: Fri, 28 Dec 2018 11:51:05 +0100 Subject: [PATCH 025/225] Use EventEmitter type from node --- types/vast-client/index.d.ts | 6 +++--- types/vast-client/vast-client-tests.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index b864a685c9..2dac79499c 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -4,9 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { EventEmitter } from 'events'; +/// -export class VASTTracker extends EventEmitter { +export class VASTTracker extends NodeJS.EventEmitter { /** * The VAST tracker constructor will process the tracking URLs of the selected ad/creative and returns an instance of VASTTracker. */ @@ -170,7 +170,7 @@ export class VASTClient { getParser(): VASTParser; } -export class VASTParser extends EventEmitter { +export class VASTParser extends NodeJS.EventEmitter { /** * util method for handling urls, it is used to make the requests. */ diff --git a/types/vast-client/vast-client-tests.ts b/types/vast-client/vast-client-tests.ts index 53ecf850fe..48622b07fb 100644 --- a/types/vast-client/vast-client-tests.ts +++ b/types/vast-client/vast-client-tests.ts @@ -136,7 +136,7 @@ const onSkip = () => { // Log a message when event 'skip' is emitted vastTracker.on('skip', onSkip); // Stop logging message -// vastTracker.off('skip', onSkip); +vastTracker.off('skip', onSkip); const player = document.getElementById('playerId') as HTMLVideoElement; From 18e4506ba16c3738847feb5b1b471dd8a1f993f0 Mon Sep 17 00:00:00 2001 From: denis Date: Wed, 19 Dec 2018 21:52:41 +0100 Subject: [PATCH 026/225] Improve dsv and fetch typing with generics --- types/d3-dsv/index.d.ts | 83 ++++++++++++++++++++------------ types/d3-fetch/d3-fetch-tests.ts | 4 ++ types/d3-fetch/index.d.ts | 69 +++++++++++++++----------- 3 files changed, 98 insertions(+), 58 deletions(-) diff --git a/types/d3-dsv/index.d.ts b/types/d3-dsv/index.d.ts index bdebc5ca01..fcfaa67339 100644 --- a/types/d3-dsv/index.d.ts +++ b/types/d3-dsv/index.d.ts @@ -15,21 +15,41 @@ /** * An object representing a DSV parsed row with values represented as strings. + * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value. */ -export interface DSVRowString { - [key: string]: string | undefined; -} +export type DSVRowString = { + [key in Columns]: string | undefined; +}; + +/** + * An object in raw format before parsing, that is with only string values. + * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value. + */ +export type DSVRaw = { + [key in keyof T]: string | undefined; +}; /** * An object representing a DSV parsed row with values represented as an arbitrary datatype, depending * on the performed parsed row mapping. * - * @deprecated + * @deprecated Use `object` instead. */ export interface DSVRowAny { [key: string]: any; } +/** + * An array object representing all deserialized rows. The array is enhanced with a property listing + * the names of the parsed columns. + */ +export interface DSVRowArray extends Array> { + /** + * List of column names. + */ + columns: Columns[]; +} + /** * An array object representing all parsed rows. The array is enhanced with a property listing * the names of the parsed columns. @@ -38,7 +58,7 @@ export interface DSVParsedArray extends Array { /** * List of column names. */ - columns: string[]; + columns: Array; } // ------------------------------------------------------------------------------------------ @@ -55,11 +75,12 @@ export interface DSVParsedArray extends Array { * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat(",").parse. + * Equivalent to `dsvFormat(",").parse`. * * @param csvString A string, which must be in the comma-separated values format. */ -export function csvParse(csvString: string): DSVParsedArray; +// tslint:disable-next-line:no-unnecessary-generics +export function csvParse(csvString: string): DSVRowArray; /** * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. * @@ -68,7 +89,7 @@ export function csvParse(csvString: string): DSVParsedArray; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat(",").parse. + * Equivalent to `dsvFormat(",").parse`. * * @param csvString A string, which must be in the comma-separated values format. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -76,9 +97,9 @@ export function csvParse(csvString: string): DSVParsedArray; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csvParse( +export function csvParse( csvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): DSVParsedArray; // csvParseRows(...) ======================================================================== @@ -92,7 +113,7 @@ export function csvParse( * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. * - * Equivalent to dsvFormat(",").parseRows. + * Equivalent to `dsvFormat(",").parseRows`. * * @param csvString A string, which must be in the comma-separated values format. */ @@ -103,7 +124,7 @@ export function csvParseRows(csvString: string): string[][]; * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. * Each row is represented as an array rather than an object. Rows may have variable length. * - * Equivalent to dsvFormat(",").parseRows. + * Equivalent to `dsvFormat(",").parseRows`. * * @param csvString A string, which must be in the comma-separated values format. * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) @@ -127,7 +148,7 @@ export function csvParseRows( * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; * the order of columns is nondeterministic. * - * Equivalent to dsvFormat(",").format. + * Equivalent to `dsvFormat(",").format`. * * @param rows Array of object rows. * @param columns An array of strings representing the column names. @@ -145,7 +166,7 @@ export function csvFormat(rows: T[], columns?: Array) * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. * If you like, you can also array.concat this result with an array of column names to generate the first row. * - * Equivalent to dsvFormat(",").formatRows. + * Equivalent to `dsvFormat(",").formatRows`. * * @param rows An array of array of string rows. */ @@ -165,11 +186,12 @@ export function csvFormatRows(rows: string[][]): string; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat("\t").parse. + * Equivalent to `dsvFormat("\t").parse`. * * @param tsvString A string, which must be in the tab-separated values format. */ -export function tsvParse(tsvString: string): DSVParsedArray; +// tslint:disable-next-line:no-unnecessary-generics +export function tsvParse(tsvString: string): DSVRowArray; /** * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. * @@ -178,7 +200,7 @@ export function tsvParse(tsvString: string): DSVParsedArray; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat("\t").parse. + * Equivalent to `dsvFormat("\t").parse`. * * @param tsvString A string, which must be in the tab-separated values format. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -186,10 +208,10 @@ export function tsvParse(tsvString: string): DSVParsedArray; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsvParse( +export function tsvParse( tsvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow | undefined | null -): DSVParsedArray; + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null +): DSVParsedArray; // tsvParseRows(...) ======================================================================== @@ -202,7 +224,7 @@ export function tsvParse( * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. * - * Equivalent to dsvFormat("\t").parseRows. + * Equivalent to `dsvFormat("\t").parseRows`. * * @param tsvString A string, which must be in the tab-separated values format. */ @@ -213,7 +235,7 @@ export function tsvParseRows(tsvString: string): string[][]; * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. * Each row is represented as an array rather than an object. Rows may have variable length. * - * Equivalent to dsvFormat("\t").parseRows. + * Equivalent to `dsvFormat("\t").parseRows`. * * @param tsvString A string, which must be in the tab-separated values format. * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) @@ -221,10 +243,10 @@ export function tsvParseRows(tsvString: string): string[][]; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsvParseRows( +export function tsvParseRows( tsvString: string, - row: (rawRow: string[], index: number) => MappedRow | undefined | null -): MappedRow[]; + row: (rawRow: string[], index: number) => ParsedRow | undefined | null +): ParsedRow[]; // tsvFormat(...) ============================================================================ @@ -237,7 +259,7 @@ export function tsvParseRows( * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; * the order of columns is nondeterministic. * - * Equivalent to dsvFormat("\t").format. + * Equivalent to `dsvFormat("\t").format`. * * @param rows Array of object rows. * @param columns An array of strings representing the column names. @@ -255,7 +277,7 @@ export function tsvFormat(rows: T[], columns?: Array) * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. * If you like, you can also array.concat this result with an array of column names to generate the first row. * - * Equivalent to dsvFormat("\t").formatRows. + * Equivalent to `dsvFormat("\t").formatRows`. * * @param rows An array of array of string rows. */ @@ -279,7 +301,8 @@ export interface DSV { * * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. */ - parse(dsvString: string): DSVParsedArray; + // tslint:disable-next-line:no-unnecessary-generics + parse(dsvString: string): DSVRowArray; /** * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. * @@ -294,9 +317,9 @@ export interface DSV { * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ - parse( + parse( dsvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): DSVParsedArray; /** diff --git a/types/d3-fetch/d3-fetch-tests.ts b/types/d3-fetch/d3-fetch-tests.ts index 4d49d86a7f..3c4ad739f1 100644 --- a/types/d3-fetch/d3-fetch-tests.ts +++ b/types/d3-fetch/d3-fetch-tests.ts @@ -35,16 +35,20 @@ const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyTy const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null; return myType; }; + let promise1: Promise>; let promise2: Promise>; + promise1 = d3Fetch.csv(url); promise1 = d3Fetch.csv(url, init); promise2 = d3Fetch.csv(url, parseRow); promise2 = d3Fetch.csv(url, init, parseRow); + promise1 = d3Fetch.dsv(';', url); promise1 = d3Fetch.dsv(';', url, init); promise2 = d3Fetch.dsv(';', url, parseRow); promise2 = d3Fetch.dsv(';', url, init, parseRow); + promise1 = d3Fetch.tsv(url); promise1 = d3Fetch.tsv(url, init); promise2 = d3Fetch.tsv(url, parseRow); diff --git a/types/d3-fetch/index.d.ts b/types/d3-fetch/index.d.ts index f6dc317784..248ed7ffc6 100644 --- a/types/d3-fetch/index.d.ts +++ b/types/d3-fetch/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for d3-fetch 1.1 // Project: https://d3js.org/d3-fetch/ // Definitions by: Hugues Stefanski +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // Last module patch version validated against: 1.1.0 -import { DSVParsedArray, DSVRowString } from 'd3-dsv'; +import { DSVParsedArray, DSVRowArray, DSVRowString } from "d3-dsv"; /** * Fetches the binary file at the specified input URL and returns it as a Promise of a Blob. @@ -33,13 +34,15 @@ export function buffer(url: string, init?: RequestInit): Promise; * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param url A valid URL string. * @param init An optional request initialization object. */ -export function csv( +export function csv( url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the CSV file at the specified input URL and returns * a promise of an array of objects representing the parsed rows. @@ -47,7 +50,8 @@ export function csv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.csvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -55,9 +59,9 @@ export function csv( * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csv( +export function csv( url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the CSV file at the specified input URL and returns @@ -68,7 +72,8 @@ export function csv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.csvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param init An request initialization object. @@ -77,10 +82,10 @@ export function csv( * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csv( +export function csv( url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** @@ -90,15 +95,17 @@ export function csv( * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. * @param init An optional request initialization object. */ -export function dsv( +export function dsv( delimiter: string, url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the DSV file with the specified delimiter character at the specified input URL and returns * a promise of an array of objects representing the parsed rows. @@ -106,7 +113,8 @@ export function dsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.parse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. @@ -115,10 +123,10 @@ export function dsv( * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function dsv( +export function dsv( delimiter: string, url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the DSV file with the specified delimiter character at the specified input URL and returns @@ -129,7 +137,8 @@ export function dsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.parse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. @@ -139,11 +148,11 @@ export function dsv( * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function dsv( +export function dsv( delimiter: string, url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** @@ -204,13 +213,15 @@ export function text(url: string, init?: RequestInit): Promise; * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param url A valid URL string. * @param init An optional request initialization object. */ -export function tsv( +export function tsv( url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the TSV file at the specified input URL and returns * a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row @@ -219,7 +230,8 @@ export function tsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.tsvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -227,9 +239,9 @@ export function tsv( * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsv( +export function tsv( url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the TSV file at the specified input URL and returns @@ -240,7 +252,8 @@ export function tsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.tsvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param init An request initialization object. @@ -249,10 +262,10 @@ export function tsv( * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsv( +export function tsv( url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** From 0dc4d3681eccddc555d9a5f1f61bd43acd3b548d Mon Sep 17 00:00:00 2001 From: denis Date: Sun, 23 Dec 2018 21:49:50 +0100 Subject: [PATCH 027/225] Update tests --- types/d3-dsv/d3-dsv-tests.ts | 100 ++++++++++++---- types/d3-fetch/d3-fetch-tests.ts | 198 ++++++++++++++++++++++--------- types/d3-fetch/index.d.ts | 2 +- 3 files changed, 220 insertions(+), 80 deletions(-) diff --git a/types/d3-dsv/d3-dsv-tests.ts b/types/d3-dsv/d3-dsv-tests.ts index 259180632f..8e05b04e61 100644 --- a/types/d3-dsv/d3-dsv-tests.ts +++ b/types/d3-dsv/d3-dsv-tests.ts @@ -21,6 +21,9 @@ const csvTestStringWithHeader = `Year,Make,Model,Length\n${csvTestString}`; const tsvTestStringWithHeader = `Year\tMake\tModel\tLength\n${tsvTestString}`; const pipedTestStringWithHeader = `Year|Make|Model|Length\n${pipedTestString}`; +type Headers = "Year" | "Make" | "Model" | "Length"; +type ParsedHeaders = "year" | "make" | "model" | "length"; + interface ParsedTestObject { year: Date | null; make: string; @@ -28,17 +31,56 @@ interface ParsedTestObject { length: number; } -let parseArray: d3Dsv.DSVParsedArray; -let parseMappedArray: d3Dsv.DSVParsedArray; - let parseRowsArray: string[][]; let parseRowsMappedArray: ParsedTestObject[]; - let parsedTestObject: ParsedTestObject; -let columns: string[]; + +let num: number; let str: string; let strMaybe: string | undefined; +let columns: string[]; +let headers: Headers[]; +let parsedHeaders: ParsedHeaders[]; + +// ------------------------------------------------------------------------------------------ +// Test Shared Types and Interfaces +// ------------------------------------------------------------------------------------------ + +declare let row: d3Dsv.DSVRowString; +strMaybe = row.property; + +declare let row2: d3Dsv.DSVRowString; +strMaybe = row2.Make; +strMaybe = row2.Property; // $ExpectError + +declare let raw: d3Dsv.DSVRaw; +strMaybe = raw.make; +strMaybe = raw.property; // $ExpectError + +declare let rowArray: d3Dsv.DSVRowArray; +strMaybe = rowArray[0].property; +columns = rowArray.columns; +num = rowArray.length; + +declare let rowArrayHeader: d3Dsv.DSVRowArray; +strMaybe = rowArrayHeader[0].Make; +strMaybe = rowArrayHeader[0].Property; // $ExpectError +headers = rowArrayHeader.columns; +num = rowArrayHeader.length; + +declare let parseMappedArray: d3Dsv.DSVParsedArray; +strMaybe = parseMappedArray[0].make; +strMaybe = parseMappedArray[0].property; // $ExpectError +parsedTestObject = parseMappedArray[0]; +parsedHeaders = parseMappedArray.columns; +num = parseMappedArray.length; + +declare let parseArray: d3Dsv.DSVParsedArray; +strMaybe = parseArray[0].property; +columns = parseArray.columns; +num = parseArray.length; + // ------------------------------------------------------------------------------------------ // Test CSV // ------------------------------------------------------------------------------------------ @@ -48,8 +90,7 @@ let strMaybe: string | undefined; // without row mapper ----------------------------------------------------------------------- parseArray = d3Dsv.csvParse(csvTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = d3Dsv.csvParse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -73,8 +114,12 @@ parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, colum return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // csvParseRows(...) ============================================================================ @@ -108,12 +153,11 @@ parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { str = d3Dsv.csvFormat(parseRowsMappedArray); str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); +str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // csvFormatRows(...) ======================================================================== -str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ +str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, @@ -129,8 +173,7 @@ str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ // without row mapper ----------------------------------------------------------------------- parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = d3Dsv.tsvParse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -154,8 +197,12 @@ parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, colum return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // tsvParseRows(...) ============================================================================ @@ -189,12 +236,11 @@ parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { str = d3Dsv.tsvFormat(parseRowsMappedArray); str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); +str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // tsvFormatRows(...) ======================================================================== -str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [ +str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, @@ -215,8 +261,7 @@ dsv = d3Dsv.dsvFormat('|'); // without row mapper ----------------------------------------------------------------------- parseArray = dsv.parse(pipedTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = dsv.parse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -240,8 +285,12 @@ parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // parseRows(...) ============================================================================ @@ -275,12 +324,11 @@ parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { str = dsv.format(parseRowsMappedArray); str = dsv.format(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); +str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // formatRows(...) ======================================================================== -str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [ +str = dsv.formatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, diff --git a/types/d3-fetch/d3-fetch-tests.ts b/types/d3-fetch/d3-fetch-tests.ts index 3c4ad739f1..8d6b862afc 100644 --- a/types/d3-fetch/d3-fetch-tests.ts +++ b/types/d3-fetch/d3-fetch-tests.ts @@ -1,66 +1,158 @@ import * as d3Fetch from 'd3-fetch'; -import { DSVParsedArray, DSVRowString } from 'd3-dsv'; +import { DSVParsedArray, DSVRaw, DSVRowString } from 'd3-dsv'; -interface MyType { - foo: string; +// ---------------------------------------------------------------------------- +// Preparatory Steps +// ---------------------------------------------------------------------------- + +type Headers = "Year" | "Make" | "Model" | "Length"; + +interface Car { + year: Date; + make: string; + model: string; + length: number; } -const url = 'foo.bar'; - -const init: RequestInit = {}; - -let p1: Promise = d3Fetch.blob(url); -p1 = d3Fetch.blob(url, init); - -let p2: Promise = d3Fetch.buffer(url); -p2 = d3Fetch.buffer(url, init); - -let p3: Promise = d3Fetch.image(url); -const imageProperties = { - width: '300px', - height: '500px' -}; -p3 = d3Fetch.image(url, imageProperties); - -let p4: Promise = d3Fetch.json(url); -p4 = d3Fetch.json(url, init); -let p5: Promise = d3Fetch.json(url); -p5 = d3Fetch.json(url, init); - -let myString: Promise; -myString = d3Fetch.text(url); -myString = d3Fetch.text(url, init); - -const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyType | undefined | null) => { - const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null; - return myType; -}; - -let promise1: Promise>; -let promise2: Promise>; - -promise1 = d3Fetch.csv(url); -promise1 = d3Fetch.csv(url, init); -promise2 = d3Fetch.csv(url, parseRow); -promise2 = d3Fetch.csv(url, init, parseRow); - -promise1 = d3Fetch.dsv(';', url); -promise1 = d3Fetch.dsv(';', url, init); -promise2 = d3Fetch.dsv(';', url, parseRow); -promise2 = d3Fetch.dsv(';', url, init, parseRow); - -promise1 = d3Fetch.tsv(url); -promise1 = d3Fetch.tsv(url, init); -promise2 = d3Fetch.tsv(url, parseRow); -promise2 = d3Fetch.tsv(url, init, parseRow); - +let anyPromise: Promise; +let arrayPromise: Promise; +let blobPromise: Promise; let docPromise: Promise; +let imagePromise: Promise; +let carPromise: Promise; +let stringPromise: Promise; +let xmlDocPromise: Promise; + +const url = 'example.org'; +const init: RequestInit = {}; +const map = new Map(); + +const imageProperties = { + width: 300, + height: 500, + crossOrigin: "anonymous", +}; + +// ---------------------------------------------------------------------------- +// Non DSV file format +// ---------------------------------------------------------------------------- + +blobPromise = d3Fetch.blob(url); +blobPromise = d3Fetch.blob(url, init); + +arrayPromise = d3Fetch.buffer(url); +arrayPromise = d3Fetch.buffer(url, init); + +imagePromise = d3Fetch.image(url); +imagePromise = d3Fetch.image(url, imageProperties); +// $ExpectError +imagePromise = d3Fetch.image(url, {width: "500px"}); // fails, string not assignable to number | undefined + +anyPromise = d3Fetch.json(url); +anyPromise = d3Fetch.json(url, init); + +carPromise = d3Fetch.json(url); +carPromise = d3Fetch.json(url, init); + +stringPromise = d3Fetch.text(url); +stringPromise = d3Fetch.text(url, init); + docPromise = d3Fetch.html(url); docPromise = d3Fetch.html(url, init); docPromise = d3Fetch.svg(url); docPromise = d3Fetch.svg(url, init); -let xmlDocPromise: Promise; xmlDocPromise = d3Fetch.xml(url); xmlDocPromise = d3Fetch.xml(url, init); + +// ---------------------------------------------------------------------------- +// DSV file format +// ---------------------------------------------------------------------------- + +let rawPromise: Promise>; +let rawPromiseHeader: Promise>>; +let parsedPromise: Promise>; + +declare const parseRowString: (rawRow: DSVRowString, index: number, columns: string[]) => Car | undefined | null; + +const parseRow = (d: DSVRowString, index: number, columns: Headers[]): Car | undefined | null => { + const item: string | undefined = d[columns[0]]; + const car = d.Make === 'Ford' ? null : + { + year: new Date(+d.Make!, 0, 1), + make: d.Make!, + model: d.Model!, + length: +d.Length!, + }; + return index % 2 === 0 ? undefined : car; +}; + +const parseRowSimple = (d: DSVRaw) => { + return { + year: new Date(+d.make!, 0, 1), + make: d.make!, + model: d.model!, + length: +d.length!, + }; +}; + +// CSV + +rawPromise = d3Fetch.csv(url); +rawPromise = d3Fetch.csv(url, init); + +rawPromiseHeader = d3Fetch.csv(url); +rawPromiseHeader = d3Fetch.csv(url, init); + +parsedPromise = d3Fetch.csv(url, parseRowString); +parsedPromise = d3Fetch.csv(url, init, parseRowString); + +parsedPromise = d3Fetch.csv(url, parseRow); +parsedPromise = d3Fetch.csv(url, init, parseRow); + +parsedPromise = d3Fetch.csv(url, parseRow); +parsedPromise = d3Fetch.csv(url, init, parseRow); +parsedPromise = d3Fetch.csv(url, parseRowSimple); + +anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!)); + +// DSV + +rawPromise = d3Fetch.dsv("|", url); +rawPromise = d3Fetch.dsv("|", url, init); + +rawPromiseHeader = d3Fetch.dsv("|", url); +rawPromiseHeader = d3Fetch.dsv("|", url, init); + +parsedPromise = d3Fetch.dsv("|", url, parseRowString); +parsedPromise = d3Fetch.dsv("|", url, init, parseRowString); + +parsedPromise = d3Fetch.dsv("|", url, parseRow); +parsedPromise = d3Fetch.dsv("|", url, init, parseRow); + +parsedPromise = d3Fetch.dsv("|", url, parseRow); +parsedPromise = d3Fetch.dsv("|", url, init, parseRow); +parsedPromise = d3Fetch.dsv("|", url, parseRowSimple); + +anyPromise = d3Fetch.dsv("|", url, (d: DSVRaw) => map.set(d.model!, +d.year!)); + +// TSV + +rawPromise = d3Fetch.tsv(url); +rawPromise = d3Fetch.tsv(url, init); + +rawPromiseHeader = d3Fetch.tsv(url); +rawPromiseHeader = d3Fetch.tsv(url, init); + +parsedPromise = d3Fetch.tsv(url, parseRowString); +parsedPromise = d3Fetch.tsv(url, init, parseRowString); + +parsedPromise = d3Fetch.tsv(url, parseRow); +parsedPromise = d3Fetch.tsv(url, init, parseRow); + +parsedPromise = d3Fetch.tsv(url, parseRow); +parsedPromise = d3Fetch.tsv(url, init, parseRow); +parsedPromise = d3Fetch.tsv(url, parseRowSimple); + +anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!)); diff --git a/types/d3-fetch/index.d.ts b/types/d3-fetch/index.d.ts index 248ed7ffc6..4110ba4a7b 100644 --- a/types/d3-fetch/index.d.ts +++ b/types/d3-fetch/index.d.ts @@ -173,7 +173,7 @@ export function html(url: string, init?: RequestInit): Promise; * @param url A valid URL string. * @param init An optional object of image properties to set. */ -export function image(url: string, init?: {[key: string]: any}): Promise; +export function image(url: string, init?: Partial): Promise; /** * Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object. From ce0ad7ff1c8fc2329dfdea2c7cf5e053b2537623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 14:20:16 +0200 Subject: [PATCH 028/225] refactor: move StellarBase into namespace --- types/stellar-sdk/index.d.ts | 859 +++++++++++++++++++---------------- 1 file changed, 459 insertions(+), 400 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d690398d0c..63748e65be 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -5,23 +5,442 @@ // Paul Selden // Max Bause // Timur Ramazanov +// Kalvis Kalniņš // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 /// -export class Account { - constructor(accountId: string, sequence: string) - accountId(): string; - sequenceNumber(): string; - incrementSequenceNumber(): void; +export namespace StellarBase { + const hash: any; // TODO + const sign: any; // TODO + const verify: any; // TODO + const FastSigning: any; // TODO + + class Account { + constructor(accountId: string, sequence: string | number) + accountId(): string; + sequenceNumber(): string; + incrementSequenceNumber(): void; + } + + class Asset { + static native(): Asset; + static fromOperation(xdr: xdr.Asset): Asset; + + constructor(code: string, issuer: string); + + getCode(): string; + getIssuer(): string; + getAssetType(): ASSET_TYPE; + isNative(): boolean; + equals(other: Asset): boolean; + toXDRObject(): xdr.Asset; + + code: string; + issuer: string; + } + + class Keypair { + static fromRawEd25519Seed(secretSeed: Buffer): Keypair; + static fromBase58Seed(secretSeed: string): Keypair; + static fromSecret(secretKey: string): Keypair; + static master(): Keypair; + static fromPublicKey(publicKey: string): Keypair; + static random(): Keypair; + + constructor(keys: { type: 'ed25519', secretKey: string } | { type: 'ed25519', Key: string }) + + publicKey(): string; + secret(): string; + rawPublicKey(): Buffer; + rawSecretKey(): Buffer; + canSign(): boolean; + sign(data: Buffer): Buffer; + signDecorated(data: Buffer): xdr.DecoratedSignature; + signatureHint(): xdr.SignatureHint; + verify(data: Buffer, signature: Buffer): boolean; + } + + const MemoNone = 'none'; + const MemoID = 'id'; + const MemoText = 'text'; + const MemoHash = 'hash'; + const MemoReturn = 'return'; + type MemoType = typeof MemoNone | typeof MemoID | typeof MemoText | typeof MemoHash | typeof MemoReturn; + class Memo { + static fromXDRObject(memo: xdr.Memo): Memo; + static hash(hash: string): Memo; + static id(id: string): Memo; + static none(): Memo; + static return(hash: string): Memo; + static text(text: string): Memo; + + constructor(type: typeof MemoNone); + constructor(type: typeof MemoID | typeof MemoText | typeof MemoHash | typeof MemoReturn, value: string) + constructor(type: typeof MemoHash | typeof MemoReturn, value: Buffer) + + type: string; + value: null | string | Buffer; + + toXDRObject(): xdr.Memo; + } + + enum Networks { + PUBLIC = 'Public Global Stellar Network ; September 2015', + TESTNET = 'Test SDF Network ; September 2015', + } + + class Network { + static use(network: Network): void; + static usePublicNetwork(): void; + static useTestNetwork(): void; + static current(): Network; + + constructor(passphrase: string) + + networkPassphrase(): string; + networkId(): string; + } + + const AuthRequiredFlag: 1; + const AuthRevocableFlag: 2; + const AuthImmutableFlag: 4; + + type TransactionOperation = + Operation.CreateAccount + | Operation.Payment + | Operation.PathPayment + | Operation.CreatePassiveOffer + | Operation.ManageOffer + | Operation.SetOptions + | Operation.ChangeTrust + | Operation.AllowTrust + | Operation.AccountMerge + | Operation.Inflation + | Operation.ManageData + | Operation.BumpSequence; + + enum OperationType { + createAccount = 'createAccount', + payment = 'payment', + pathPayment = 'pathPayment', + createPassiveOffer = 'createPassiveOffer', + manageOffer = 'manageOffer', + setOptions = 'setOptions', + changeTrust = 'changeTrust', + allowTrust = 'allowTrust', + accountMerge = 'accountMerge', + inflation = 'inflation', + manageData = 'manageData', + bumpSequence = 'bumpSequence', + } + + namespace Operation { + interface Operation { + type: OperationType; + source: string | null; + } + interface AccountMerge extends Operation { + type: OperationType.accountMerge; + destination: string; + } + interface AccountMergeOptions { + destination: string; + source?: string; + } + function accountMerge(options: AccountMergeOptions): xdr.Operation; + + interface AllowTrust extends Operation { + type: OperationType.allowTrust; + trustor: string; + assetCode: string; + authorize: boolean; + } + interface AllowTrustOptions { + trustor: string; + assetCode: string; + authorize: boolean; + source?: string; + } + function allowTrust(options: AllowTrustOptions): xdr.Operation; + + interface ChangeTrust extends Operation { + type: OperationType.changeTrust; + line: Asset; + limit: string | number; + } + interface ChangeTrustOptions { + asset: Asset; + limit?: string; + source?: string; + } + function changeTrust(options: ChangeTrustOptions): xdr.Operation; + + interface CreateAccount extends Operation { + type: OperationType.createAccount; + source: string; + destination: string; + startingBalance: string | number; + } + interface CreateAccountOptions { + destination: string; + startingBalance: string; + source?: string; + } + function createAccount(options: CreateAccountOptions): xdr.Operation; + + interface CreatePassiveOffer extends Operation { + type: OperationType.createPassiveOffer; + selling: Asset; + buying: Asset; + amount: string | number; + price: string | number; + } + interface CreatePassiveOfferOptions { + selling: Asset; + buying: Asset; + amount: string; + price: number | string | object; + source?: string; + } + function createPassiveOffer(options: CreatePassiveOfferOptions): xdr.Operation; + + interface Inflation extends Operation { + type: OperationType.inflation; + } + function inflation(options: { source?: string }): xdr.Operation; + + interface ManageData extends Operation { + type: OperationType.manageData; + name: string; + value: Buffer; + } + interface ManageDataOptions { + name: string; + value: string | Buffer; + source?: string; + } + function manageData(options: ManageDataOptions): xdr.Operation; + + interface ManageOffer extends Operation { + type: OperationType.manageOffer; + selling: Asset; + buying: Asset; + amount: string | number; + price: string | number; + offerId: string; + } + interface ManageOfferOptions extends CreatePassiveOfferOptions { + offerId?: number | string; + } + function manageOffer(options: ManageOfferOptions): xdr.Operation; + + interface PathPayment extends Operation { + type: OperationType.pathPayment; + sendAsset: Asset; + sendMax: string | number; + destination: string; + destAsset: Asset; + destAmount: string | number; + path: Asset[]; + } + interface PathPaymentOptions { + sendAsset: Asset; + sendMax: string; + destination: string; + destAsset: Asset; + destAmount: string; + path: Asset[]; + source?: string; + } + function pathPayment(options: PathPaymentOptions): xdr.Operation; + + interface Payment extends Operation { + type: OperationType.payment; + destination: string; + asset: Asset; + amount: string | number; + } + interface PaymentOptions { + destination: string; + asset: Asset; + amount: string; + source?: string; + } + function payment(options: PaymentOptions): xdr.Operation; + + /* + * Required = 1 << 0 + * Revocable = 1 << 1 + * Immutable = 1 << 2 + */ + enum AuthFlags { + Required = 1, + Revocable = 2, + Immutable = 4, + } + interface Signer { + ed25519PublicKey?: string; + sha256Hash?: Buffer | string; + preAuthTx?: Buffer | string; + weight?: number | string; + } + interface SetOptions extends Operation { + type: OperationType.setOptions; + inflationDest?: string; + clearFlags?: AuthFlags; + setFlags?: AuthFlags; + masterWeight?: number | string; + lowThreshold?: number | string; + medThreshold?: number | string; + highThreshold?: number | string; + homeDomain?: string; + signer?: Signer; + } + interface SetOptionsOptions { + inflationDest?: string; + clearFlags?: AuthFlags; + setFlags?: AuthFlags; + masterWeight?: number | string; + lowThreshold?: number | string; + medThreshold?: number | string; + highThreshold?: number | string; + signer?: Signer; + homeDomain?: string; + source?: string; + } + function setOptions(options: SetOptionsOptions): xdr.Operation; + + interface BumpSequence extends Operation { + type: OperationType.bumpSequence; + bumpTo: string; + } + interface BumpSequenceOptions { + bumpTo: string; + source?: string; + } + function bumpSequence(options: BumpSequenceOptions): xdr.Operation; + + function fromXDRObject(xdrOperation: xdr.Operation): T; + } + + namespace StrKey { + function encodeEd25519PublicKey(data: Buffer): string; + function decodeEd25519PublicKey(data: string): Buffer; + function isValidEd25519PublicKey(Key: string): boolean; + + function encodeEd25519SecretSeed(data: Buffer): string; + function decodeEd25519SecretSeed(data: string): Buffer; + function isValidEd25519SecretSeed(seed: string): boolean; + + function encodePreAuthTx(data: Buffer): string; + function decodePreAuthTx(data: string): Buffer; + + function encodeSha256Hash(data: Buffer): string; + function decodeSha256Hash(data: string): Buffer; + } + + class Transaction { + constructor(envelope: string | xdr.TransactionEnvelope) + hash(): Buffer; + sign(...keypairs: Keypair[]): void; + signatureBase(): Buffer; + signHashX(preimage: Buffer | string): void; + toEnvelope(): xdr.TransactionEnvelope; + + operations: TransactionOperation[]; + sequence: number; + fee: number; + source: string; + memo: Memo; + signatures: xdr.DecoratedSignature[]; + } + + class TransactionBuilder { + constructor(sourceAccount: Account, options?: TransactionBuilder.TransactionBuilderOptions) + addOperation(operation: xdr.Operation): this; + addMemo(memo: Memo): this; + build(): Transaction; + } + + namespace TransactionBuilder { + interface TransactionBuilderOptions { + fee?: number; + timebounds?: { + minTime?: number | string + maxTime?: number | string + }; + memo?: Memo; + } + } + + namespace xdr { + class XDRStruct { + static fromXDR(xdr: Buffer): XDRStruct; + + toXDR(base?: string): Buffer; + toXDR(encoding: string): string; + } + class Operation extends XDRStruct { + static fromXDR(xdr: Buffer): Operation; + } + class Asset extends XDRStruct { + static fromXDR(xdr: Buffer): Asset; + } + class Memo extends XDRStruct { + static fromXDR(xdr: Buffer): Memo; + } + class TransactionEnvelope extends XDRStruct { + static fromXDR(xdr: Buffer): TransactionEnvelope; + } + class DecoratedSignature extends XDRStruct { + static fromXDR(xdr: Buffer): DecoratedSignature; + + constructor(keys: { hint: SignatureHint, signature: Signature }) + + hint(): SignatureHint; + signature(): Buffer; + } + type SignatureHint = Buffer; + type Signature = Buffer; + + class TransactionResult extends XDRStruct { + static fromXDR(xdr: Buffer): TransactionResult; + } + } } +// Re-export StellarBase +export import Account = StellarBase.Account; +export import Asset = StellarBase.Asset; +export import FastSigning = StellarBase.FastSigning; +export import Keypair = StellarBase.Keypair; +export import Memo = StellarBase.Memo; +export import MemoHash = StellarBase.MemoHash; +export import MemoID = StellarBase.MemoID; +export import MemoNone = StellarBase.MemoNone; +export import MemoReturn = StellarBase.MemoReturn; +export import MemoText = StellarBase.MemoText; +export import MemoType = StellarBase.MemoType; +export import Network = StellarBase.Network; +export import Networks = StellarBase.Networks; +export import Operation = StellarBase.Operation; +export import OperationType = StellarBase.OperationType; +export import StrKey = StellarBase.StrKey; +export import TransactionOperation = StellarBase.TransactionOperation; +export import hash = StellarBase.hash; +export import sign = StellarBase.sign; +export import verify = StellarBase.verify; +export import Transaction = StellarBase.Transaction; +export import TransactionBuilder = StellarBase.TransactionBuilder; +export import xdr = StellarBase.xdr; + export class CallBuilder { constructor(serverUrl: string) call(): Promise>; cursor(cursor: string): this; - limit(limit: number): this; + limit(limit: number | string): this; order(direction: 'asc' | 'desc'): this; stream(options?: { onmessage?: (record: T) => void, onerror?: (error: Error) => void }): () => void; } @@ -65,6 +484,25 @@ export type CallFunction = () => Promise; export type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; +export enum ASSET_TYPE { + native = 'native', + credit4 = 'credit_alphanum4', + credit12 = 'credit_alphanum12', +} + +export interface BalanceLineNative { + balance: string; + asset_type: ASSET_TYPE.native; +} +export interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; + asset_code: string; + asset_issuer: string; +} +export type BalanceLine = BalanceLineNative | BalanceLineAsset; + export interface AccountRecord extends Record { id: string; paging_token: string; @@ -80,19 +518,7 @@ export interface AccountRecord extends Record { auth_required: boolean auth_revocable: boolean }; - balances: Array< - { - balance: string - asset_type: 'native' - } | - { - balance: string - limit: string - asset_type: 'credit_alphanum4' | 'credit_alphanum12' - asset_code: string - asset_issuer: string - } - >; + balances: BalanceLine[]; signers: Array< { public_key: string @@ -111,7 +537,7 @@ export interface AccountRecord extends Record { } export interface AssetRecord extends Record { - asset_type: 'credit_alphanum4' | 'credit_alphanum12'; + asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; asset_code: string; asset_issuer: string; paging_token: string; @@ -129,6 +555,7 @@ export interface EffectRecord extends Record { starting_balance: string; type_i: string; type: string; + amount?: any; operation?: CallFunction; precedes?: CallFunction; @@ -178,6 +605,7 @@ export interface BaseOperationRecord extends Record { paging_token: string; type: string; type_i: number; + source_account: string; self: CallFunction; succeeds: CallFunction; @@ -390,6 +818,8 @@ export interface TransactionRecord extends Record { result_xdr: string; result_meta_xdr: string; memo: string; + envelope: any; + memo_type: any; account: CallFunction; effects: CallCollectionFunction; @@ -419,19 +849,7 @@ export class AccountResponse implements AccountRecord { auth_required: boolean auth_revocable: boolean }; - balances: Array< - { - balance: string - asset_type: 'native' - } | - { - balance: string - limit: string - asset_type: 'credit_alphanum4' | 'credit_alphanum12' - asset_code: string - asset_issuer: string - } - >; + balances: BalanceLine[]; signers: Array< { public_key: string @@ -442,6 +860,7 @@ export class AccountResponse implements AccountRecord { data_attr: { [key: string]: string }; + inflation_destination?: any; effects: CallCollectionFunction; offers: CallCollectionFunction; @@ -454,23 +873,6 @@ export class AccountResponse implements AccountRecord { incrementSequenceNumber(): void; } -export class Asset { - static native(): Asset; - static fromOperation(xdr: xdr.Asset): Asset; - - constructor(code: string, issuer: string) - - getCode(): string; - getIssuer(): string; - getAssetType(): 'native' | 'credit_alphanum4' | 'credit_alphanum12'; - isNative(): boolean; - equals(other: Asset): boolean; - toXDRObject(): xdr.Asset; - - code: string; - issuer: string; -} - export class AssetsCallBuilder extends CallBuilder { forCode(value: string): this; forIssuer(value: string): this; @@ -510,267 +912,8 @@ export class FederationServer { export class LedgerCallBuilder extends CallBuilder { } -export class Memo { - static fromXDRObject(memo: xdr.Memo): Memo; - static hash(hash: string): Memo; - static id(id: string): Memo; - static none(): Memo; - static return(hash: string): Memo; - static text(text: string): Memo; - - constructor(type: 'none'); - constructor(type: 'id' | 'text' | 'hash' | 'return', value: string) - constructor(type: 'hash' | 'return', value: Buffer) - - type: string; - value: null | string | Buffer; - - toXDRObject(): xdr.Memo; -} - -export const MemoNone = 'none'; -export const MemoID = 'id'; -export const MemoText = 'text'; -export const MemoHash = 'hash'; -export const MemoReturn = 'return'; - -export enum Networks { - PUBLIC = 'Public Global Stellar Network ; September 2015', - TESTNET = 'Test SDF Network ; September 2015', -} - -export class Network { - static use(network: Network): void; - static usePublicNetwork(): void; - static useTestNetwork(): void; - static current(): Network; - - constructor(passphrase: string) - - networkPassphrase(): string; - networkId(): string; -} - export class OfferCallBuilder extends CallBuilder { } -export type TransactionOperation = - Operation.CreateAccount - | Operation.Payment - | Operation.PathPayment - | Operation.CreatePassiveOffer - | Operation.ManageOffer - | Operation.SetOptions - | Operation.ChangeTrust - | Operation.AllowTrust - | Operation.AccountMerge - | Operation.Inflation - | Operation.ManageData - | Operation.BumpSequence; - -export enum OperationType { - createAccount = 'createAccount', - payment = 'payment', - pathPayment = 'pathPayment', - createPassiveOffer = 'createPassiveOffer', - manageOffer = 'manageOffer', - setOptions = 'setOptions', - changeTrust = 'changeTrust', - allowTrust = 'allowTrust', - accountMerge = 'accountMerge', - inflation = 'inflation', - manageData = 'manageData', - bumpSequence = 'bumpSequence', -} - -export namespace Operation { - interface Operation { - type: OperationType; - source: string | null; - } - interface AccountMerge extends Operation { - type: OperationType.accountMerge; - destination: string; - } - interface AccountMergeOptions { - destination: string; - source?: string; - } - function accountMerge(options: AccountMergeOptions): xdr.Operation; - - interface AllowTrust extends Operation { - type: OperationType.allowTrust; - trustor: string; - assetCode: string; - authorize: boolean; - } - interface AllowTrustOptions { - trustor: string; - assetCode: string; - authorize: boolean; - source?: string; - } - function allowTrust(options: AllowTrustOptions): xdr.Operation; - - interface ChangeTrust extends Operation { - type: OperationType.changeTrust; - line: Asset; - limit: string | number; - } - interface ChangeTrustOptions { - asset: Asset; - limit?: string; - source?: string; - } - function changeTrust(options: ChangeTrustOptions): xdr.Operation; - - interface CreateAccount extends Operation { - type: OperationType.createAccount; - source: string; - destination: string; - startingBalance: string | number; - } - interface CreateAccountOptions { - destination: string; - startingBalance: string; - source?: string; - } - function createAccount(options: CreateAccountOptions): xdr.Operation; - - interface CreatePassiveOffer extends Operation { - type: OperationType.createPassiveOffer; - selling: Asset; - buying: Asset; - amount: string | number; - price: string | number; - } - interface CreatePassiveOfferOptions { - selling: Asset; - buying: Asset; - amount: string; - price: number | string | object; - source?: string; - } - function createPassiveOffer(options: CreatePassiveOfferOptions): xdr.Operation; - - interface Inflation extends Operation { - type: OperationType.inflation; - } - function inflation(options: { source?: string }): xdr.Operation; - - interface ManageData extends Operation { - type: OperationType.manageData; - name: string; - value: string; - } - interface ManageDataOptions { - name: string; - value: string | Buffer; - source?: string; - } - function manageData(options: ManageDataOptions): xdr.Operation; - - interface ManageOffer extends Operation { - type: OperationType.manageOffer; - selling: Asset; - buying: Asset; - amount: string | number; - price: string | number; - offerId: string; - } - interface ManageOfferOptions extends CreatePassiveOfferOptions { - offerId: number | string; - } - function manageOffer(options: ManageOfferOptions): xdr.Operation; - - interface PathPayment extends Operation { - type: OperationType.pathPayment; - sendAsset: Asset; - sendMax: string | number; - destination: string; - destAsset: Asset; - destAmount: string | number; - path: Asset[]; - } - interface PathPaymentOptions { - sendAsset: Asset; - sendMax: string; - destination: string; - destAsset: Asset; - destAmount: string; - path: Asset[]; - source?: string; - } - function pathPayment(options: PathPaymentOptions): xdr.Operation; - - interface Payment extends Operation { - type: OperationType.payment; - destination: string; - asset: Asset; - amount: string | number; - } - interface PaymentOptions { - destination: string; - asset: Asset; - amount: string; - source?: string; - } - function payment(options: PaymentOptions): xdr.Operation; - - /* - * Required = 1 << 0 - * Revocable = 1 << 1 - * Immutable = 1 << 2 - */ - enum AuthFlags { - Required = 1, - Revocable = 2, - Immutable = 4, - } - interface Signer { - ed25519PublicKey?: string; - sha256Hash?: Buffer | string; - preAuthTx?: Buffer | string; - weight?: number | string; - } - interface SetOptions extends Operation { - type: OperationType.setOptions; - inflationDest?: string; - clearFlags?: AuthFlags; - setFlags?: AuthFlags; - masterWeight?: number | string; - lowThreshold?: number | string; - medThreshold?: number | string; - highThreshold?: number | string; - homeDomain?: string; - signer?: Signer; - } - interface SetOptionsOptions { - inflationDest?: string; - clearFlags?: AuthFlags; - setFlags?: AuthFlags; - masterWeight?: number | string; - lowThreshold?: number | string; - medThreshold?: number | string; - highThreshold?: number | string; - signer?: Signer; - homeDomain?: string; - source?: string; - } - function setOptions(options: SetOptionsOptions): xdr.Operation; - - interface BumpSequence extends Operation { - type: OperationType.bumpSequence; - bumpTo: string; - } - interface BumpSequenceOptions { - bumpTo: string; - source?: string; - } - function bumpSequence(options: BumpSequenceOptions): xdr.Operation; - - function fromXDRObject(xdrOperation: xdr.Operation): T; -} - export class OperationCallBuilder extends CallBuilder { forAccount(accountId: string): this; forLedger(sequence: string): this; @@ -784,8 +927,12 @@ export class PaymentCallBuilder extends CallBuilder { forTransaction(transactionId: string): this; } +export interface ServerOptions { + allowHttp: boolean; +} + export class Server { - constructor(serverURL: string, options?: { allowHttp: boolean }) + constructor(serverURL: string, options?: ServerOptions) accounts(): AccountCallBuilder; assets(): AssetsCallBuilder; effects(): EffectCallBuilder; @@ -801,7 +948,7 @@ export class Server { destinationAmount: string, ): PathCallBuilder; payments(): PaymentCallBuilder; - submitTransaction(transaction: Transaction): Promise; + submitTransaction(transaction: Transaction): Promise; tradeAggregation( base: Asset, counter: Asset, @@ -811,22 +958,8 @@ export class Server { ): TradeAggregationCallBuilder; trades(): TradesCallBuilder; transactions(): TransactionCallBuilder; -} -export namespace StrKey { - function encodeEd25519PublicKey(data: Buffer): string; - function decodeEd25519PublicKey(data: string): Buffer; - function isValidEd25519PublicKey(Key: string): boolean; - - function encodeEd25519SecretSeed(data: Buffer): string; - function decodeEd25519SecretSeed(data: string): Buffer; - function isValidEd25519SecretSeed(seed: string): boolean; - - function encodePreAuthTx(data: Buffer): string; - function decodePreAuthTx(data: string): Buffer; - - function encodeSha256Hash(data: Buffer): string; - function decodeSha256Hash(data: string): Buffer; + serverURL: any; // TODO: require("urijs") } export class TradeAggregationCallBuilder extends CallBuilder { } @@ -835,86 +968,12 @@ export class TradesCallBuilder extends CallBuilder { forOffer(offerId: string): this; } -export class Transaction { - constructor(envelope: string | xdr.TransactionEnvelope) - hash(): Buffer; - sign(...keypairs: Keypair[]): void; - signatureBase(): Buffer; - signHashX(preimage: Buffer | string): void; - toEnvelope(): xdr.TransactionEnvelope; - - operations: TransactionOperation[]; - sequence: number; - fee: number; - source: string; - memo: Memo; - signatures: xdr.DecoratedSignature[]; -} - -export class TransactionBuilder { - constructor(sourceAccount: Account, options?: TransactionBuilder.TransactionBuilderOptions) - addOperation(operation: xdr.Operation): this; - addMemo(memo: Memo): this; - build(): Transaction; -} - -export namespace TransactionBuilder { - interface TransactionBuilderOptions { - fee?: number; - timebounds?: { - minTime?: number | string - maxTime?: number | string - }; - memo?: Memo; - } -} - export class TransactionCallBuilder extends CallBuilder { transaction(transactionId: string): this; forAccount(accountId: string): this; forLedger(sequence: string | number): this; } -export class Keypair { - static fromRawEd25519Seed(secretSeed: Buffer): Keypair; - static fromSecret(secretKey: string): Keypair; - static master(): Keypair; - static fromPublicKey(publicKey: string): Keypair; - static random(): Keypair; - - constructor(keys: { type: 'ed25519', secretKey: string } | { type: 'ed25519', Key: string }) - - publicKey(): string; - secret(): string; - rawPublicKey(): Buffer; - rawSecretKey(): Buffer; - canSign(): boolean; - sign(data: Buffer): Buffer; - signatureHint(): xdr.SignatureHint; - verify(data: Buffer, signature: Buffer): boolean; -} - -export namespace xdr { - class XDRStruct { - static fromXDR(xdr: Buffer): XDRStruct; - - toXDR(): Buffer; - toXDR(encoding: string): string; - } - class Operation extends XDRStruct { } - class Asset extends XDRStruct { } - class Memo extends XDRStruct { } - class TransactionEnvelope extends XDRStruct { } - class DecoratedSignature extends XDRStruct { - constructor(keys: { hint: SignatureHint, signature: Signature }) - - hint(): SignatureHint; - signature(): Buffer; - } - type SignatureHint = Buffer; - type Signature = Buffer; -} - export namespace StellarTomlResolver { interface StellarTomlResolveOptions { allowHttp?: boolean; From 84b8d1a7f16a561d8edda3d2b25c744b2b696624 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 14:34:04 +0200 Subject: [PATCH 029/225] fix: FastSigning, hash, sign, verify --- types/stellar-sdk/index.d.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 63748e65be..92ca938e2b 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -12,11 +12,6 @@ /// export namespace StellarBase { - const hash: any; // TODO - const sign: any; // TODO - const verify: any; // TODO - const FastSigning: any; // TODO - class Account { constructor(accountId: string, sequence: string | number) accountId(): string; @@ -41,6 +36,8 @@ export namespace StellarBase { issuer: string; } + const FastSigning: boolean; + class Keypair { static fromRawEd25519Seed(secretSeed: Buffer): Keypair; static fromBase58Seed(secretSeed: string): Keypair; @@ -409,6 +406,10 @@ export namespace StellarBase { static fromXDR(xdr: Buffer): TransactionResult; } } + + function hash(data: Buffer): Buffer; + function sign(data: Buffer, rawSecret: Buffer): Buffer; + function verify(data: Buffer, signature: Buffer, rawPublicKey: Buffer): boolean; } // Re-export StellarBase @@ -428,12 +429,12 @@ export import Networks = StellarBase.Networks; export import Operation = StellarBase.Operation; export import OperationType = StellarBase.OperationType; export import StrKey = StellarBase.StrKey; +export import Transaction = StellarBase.Transaction; +export import TransactionBuilder = StellarBase.TransactionBuilder; export import TransactionOperation = StellarBase.TransactionOperation; export import hash = StellarBase.hash; export import sign = StellarBase.sign; export import verify = StellarBase.verify; -export import Transaction = StellarBase.Transaction; -export import TransactionBuilder = StellarBase.TransactionBuilder; export import xdr = StellarBase.xdr; export class CallBuilder { From 8b828727e769ada075d683d206fc3c5f298115ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 14:40:08 +0200 Subject: [PATCH 030/225] fix: NetworkError --- types/stellar-sdk/index.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 92ca938e2b..acb05e02a9 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -437,6 +437,15 @@ export import sign = StellarBase.sign; export import verify = StellarBase.verify; export import xdr = StellarBase.xdr; +export class NetworkError extends Error { + private response: any; + constructor(message: string, response: any) + getResponse(): any; +} +export class NotFoundError extends NetworkError {} +export class BadRequestError extends NetworkError {} +export class BadResponseError extends NetworkError {} + export class CallBuilder { constructor(serverUrl: string) call(): Promise>; From 8d8c9f33ee8ec180b1c34ed10f2b2b024d8058a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 14:48:23 +0200 Subject: [PATCH 031/225] refactor: move Config --- types/stellar-sdk/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index acb05e02a9..4b988d76aa 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -446,6 +446,12 @@ export class NotFoundError extends NetworkError {} export class BadRequestError extends NetworkError {} export class BadResponseError extends NetworkError {} +export namespace Config { + function setAllowHttp(allow: boolean): void; + function isAllowHttp(): boolean; + function setDefault(): void; +} + export class CallBuilder { constructor(serverUrl: string) call(): Promise>; @@ -888,12 +894,6 @@ export class AssetsCallBuilder extends CallBuilder { forIssuer(value: string): this; } -export namespace Config { - function setAllowHttp(allow: boolean): void; - function isAllowHttp(): boolean; - function setDefault(): void; -} - export class EffectCallBuilder extends CallBuilder { forAccount(accountId: string): this; forLedger(sequence: string): this; From 52182e8890bf8ff09bfa0fd170138135b99466af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 14:49:28 +0200 Subject: [PATCH 032/225] refactor: move FederationServer --- types/stellar-sdk/index.d.ts | 38 ++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 4b988d76aa..85201e47de 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -901,25 +901,6 @@ export class EffectCallBuilder extends CallBuilder { forTransaction(transactionId: string): this; } -export interface FederationRecord { - account_id: string; - memo_type?: string; - memo?: string; -} - -export interface FederationOptions { - allowHttp: boolean; -} -export class FederationServer { - static createForDomain(domain: string, options?: FederationOptions): Promise; - static resolve(value: string, options?: FederationOptions): Promise; - - constructor(serverURL: string, domain: string, options?: FederationOptions) - resolveAccountId(account: string): Promise; - resolveAddress(address: string): Promise; - resolveTransactionId(transactionId: string): Promise; -} - export class LedgerCallBuilder extends CallBuilder { } export class OfferCallBuilder extends CallBuilder { } @@ -984,6 +965,25 @@ export class TransactionCallBuilder extends CallBuilder { forLedger(sequence: string | number): this; } +export interface FederationRecord { + account_id: string; + memo_type?: string; + memo?: string; +} + +export interface FederationOptions { + allowHttp: boolean; +} +export class FederationServer { + static createForDomain(domain: string, options?: FederationOptions): Promise; + static resolve(value: string, options?: FederationOptions): Promise; + + constructor(serverURL: string, domain: string, options?: FederationOptions) + resolveAccountId(account: string): Promise; + resolveAddress(address: string): Promise; + resolveTransactionId(transactionId: string): Promise; +} + export namespace StellarTomlResolver { interface StellarTomlResolveOptions { allowHttp?: boolean; From cbedf99049f47194205124c0123265165a1fbca7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:03:37 +0200 Subject: [PATCH 033/225] feat: introduce and organize namespace Server BREAKING CHANGES: Need to prefix `Server.` to plenty of stuff. --- types/stellar-sdk/index.d.ts | 992 ++++++++++++++++++----------------- 1 file changed, 497 insertions(+), 495 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 85201e47de..a8b8317c2d 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -412,7 +412,7 @@ export namespace StellarBase { function verify(data: Buffer, signature: Buffer, rawPublicKey: Buffer): boolean; } -// Re-export StellarBase +// Re-StellarBase export import Account = StellarBase.Account; export import Asset = StellarBase.Asset; export import FastSigning = StellarBase.FastSigning; @@ -452,517 +452,519 @@ export namespace Config { function setDefault(): void; } -export class CallBuilder { - constructor(serverUrl: string) - call(): Promise>; - cursor(cursor: string): this; - limit(limit: number | string): this; - order(direction: 'asc' | 'desc'): this; - stream(options?: { onmessage?: (record: T) => void, onerror?: (error: Error) => void }): () => void; -} - -export interface CollectionPage { - records: T[]; - next: () => Promise>; - prev: () => Promise>; -} - -export interface Record { - _links: { - [key: string]: RecordLink - }; -} - -export interface RecordLink { - href: string; - templated?: boolean; -} - -/* Due to a bug with the recursive function requests */ -export interface CollectionRecord { - _links: { - next: RecordLink - prev: RecordLink - self: RecordLink - }; - _embedded: { - records: T[] - }; -} - -export interface CallFunctionTemplateOptions { - cursor?: string | number; - limit?: number; - order?: 'asc' | 'desc'; -} - -export type CallFunction = () => Promise; -export type CallCollectionFunction = - (options?: CallFunctionTemplateOptions) => Promise>; - -export enum ASSET_TYPE { - native = 'native', - credit4 = 'credit_alphanum4', - credit12 = 'credit_alphanum12', -} - -export interface BalanceLineNative { - balance: string; - asset_type: ASSET_TYPE.native; -} -export interface BalanceLineAsset { - balance: string; - limit: string; - asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; - asset_code: string; - asset_issuer: string; -} -export type BalanceLine = BalanceLineNative | BalanceLineAsset; - -export interface AccountRecord extends Record { - id: string; - paging_token: string; - account_id: string; - sequence: number; - subentry_count: number; - thresholds: { - low_threshold: number - med_threshold: number - high_threshold: number - }; - flags: { - auth_required: boolean - auth_revocable: boolean - }; - balances: BalanceLine[]; - signers: Array< - { - public_key: string - weight: number - } - >; - data: (options: {value: string}) => Promise<{value: string}>; - data_attr: { - [key: string]: string - }; - effects: CallCollectionFunction; - offers: CallCollectionFunction; - operations: CallCollectionFunction; - payments: CallCollectionFunction; - trades: CallCollectionFunction; -} - -export interface AssetRecord extends Record { - asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; - asset_code: string; - asset_issuer: string; - paging_token: string; - amount: string; - num_accounts: number; - flags: { - auth_required: boolean - auth_revocable: boolean - }; -} - -export interface EffectRecord extends Record { - account: string; - paging_token: string; - starting_balance: string; - type_i: string; - type: string; - amount?: any; - - operation?: CallFunction; - precedes?: CallFunction; - succeeds?: CallFunction; -} - -export interface LedgerRecord extends Record { - id: string; - paging_token: string; - hash: string; - prev_hash: string; - sequence: number; - transaction_count: number; - operation_count: number; - closed_at: string; - total_coins: string; - fee_pool: string; - base_fee: number; - base_reserve: string; - max_tx_set_size: number; - protocol_version: number; - header_xdr: string; - base_fee_in_stroops: number; - base_reserve_in_stroops: number; - - effects: CallCollectionFunction; - operations: CallCollectionFunction; - self: CallFunction; - transactions: CallCollectionFunction; -} - -export interface OfferRecord extends Record { - id: string; - paging_token: string; - seller_attr: string; - selling: Asset; - buying: Asset; - amount: string; - price_r: { numerator: number, denominator: number }; - price: string; - - seller?: CallFunction; -} - -export interface BaseOperationRecord extends Record { - id: string; - paging_token: string; - type: string; - type_i: number; - source_account: string; - - self: CallFunction; - succeeds: CallFunction; - precedes: CallFunction; - effects: CallCollectionFunction; - transaction: CallFunction; -} - -export interface CreateAccountOperationRecord extends BaseOperationRecord { - type: 'create_account'; - account: string; - funder: string; - starting_balance: string; -} - -export interface PaymentOperationRecord extends BaseOperationRecord { - type: 'payment'; - from: string; - to: string; - asset_type: string; - asset_code?: string; - asset_issuer?: string; - amount: string; - - sender: CallFunction; - receiver: CallFunction; -} - -export interface PathPaymentOperationRecord extends BaseOperationRecord { - type: 'path_payment'; - from: string; - to: string; - asset_code?: string; - asset_issuer?: string; - asset_type: string; - amount: string; - source_asset_code?: string; - source_asset_issuer?: string; - source_asset_type: string; - source_max: string; - source_amount: string; -} - -export interface ManageOfferOperationRecord extends BaseOperationRecord { - type: 'manage_offer'; - offer_id: number; - amount: string; - buying_asset_code?: string; - buying_asset_issuer?: string; - buying_asset_type: string; - price: string; - price_r: { numerator: number, denominator: number }; - selling_asset_code?: string; - selling_asset_issuer?: string; - selling_asset_type: string; -} - -export interface PassiveOfferOperationRecord extends BaseOperationRecord { - type: 'create_passive_offer'; - offer_id: number; - amount: string; - buying_asset_code?: string; - buying_asset_issuer?: string; - buying_asset_type: string; - price: string; - price_r: { numerator: number, denominator: number }; - selling_asset_code?: string; - selling_asset_issuer?: string; - selling_asset_type: string; -} - -export interface SetOptionsOperationRecord extends BaseOperationRecord { - type: 'set_options'; - signer_key?: string; - signer_weight?: number; - master_key_weight?: number; - low_threshold?: number; - med_threshold?: number; - high_threshold?: number; - home_domain?: string; - set_flags: Array<(1 | 2)>; - set_flags_s: Array<('auth_required_flag' | 'auth_revocable_flag')>; - clear_flags: Array<(1 | 2)>; - clear_flags_s: Array<('auth_required_flag' | 'auth_revocable_flag')>; -} - -export interface ChangeTrustOperationRecord extends BaseOperationRecord { - type: 'change_trust'; - asset_code: string; - asset_issuer: string; - asset_type: string; - trustee: string; - trustor: string; - limit: string; -} - -export interface AllowTrustOperationRecord extends BaseOperationRecord { - type: 'allow_trust'; - asset_code: string; - asset_issuer: string; - asset_type: string; - authorize: boolean; - trustee: string; - trustor: string; -} - -export interface AccountMergeOperationRecord extends BaseOperationRecord { - type: 'account_merge'; - into: string; -} - -export interface InflationOperationRecord extends BaseOperationRecord { - type: 'inflation'; -} - -export interface ManageDataOperationRecord extends BaseOperationRecord { - type: 'manage_data'; - name: string; - value: string; -} - -export interface BumpSequenceOperationRecord extends BaseOperationRecord { - type: 'bump_sequence'; - bump_to: string; -} - -export type OperationRecord = CreateAccountOperationRecord - | PaymentOperationRecord - | PathPaymentOperationRecord - | ManageOfferOperationRecord - | PassiveOfferOperationRecord - | SetOptionsOperationRecord - | ChangeTrustOperationRecord - | AllowTrustOperationRecord - | AccountMergeOperationRecord - | InflationOperationRecord - | ManageDataOperationRecord - | BumpSequenceOperationRecord; - -export interface OrderbookRecord extends Record { - bids: Array<{ price_r: {}, price: number, amount: string }>; - asks: Array<{ price_r: {}, price: number, amount: string }>; - selling: Asset; - buying: Asset; -} - -export interface PaymentPathRecord extends Record { - path: Array<{ - asset_code: string - asset_issuer: string - asset_type: string - }>; - source_amount: string; - source_asset_type: string; - source_asset_code: string; - source_asset_issuer: string; - destination_amount: string; - destination_asset_type: string; - destination_asset_code: string; - destination_asset_issuer: string; -} - -export interface TradeRecord extends Record { - id: string; - paging_token: string; - ledger_close_time: string; - base_account: string; - base_amount: string; - base_asset_type: string; - base_asset_code: string; - base_asset_issuer: string; - counter_account: string; - counter_amount: string; - counter_asset_type: string; - counter_asset_code: string; - counter_asset_issuer: string; - base_is_seller: boolean; - - base: CallFunction; - counter: CallFunction; - operation: CallFunction; -} - -export interface TradeAggregationRecord extends Record { - timestamp: string; - trade_count: number; - base_volume: string; - counter_volume: string; - avg: string; - high: string; - low: string; - open: string; - close: string; -} - -export interface TransactionRecord extends Record { - id: string; - paging_token: string; - hash: string; - ledger_attr: number; - created_at: string; - max_fee: number; - fee_paid: number; - operation_count: number; - result_code: number; - result_code_s: string; - source_account: string; - source_account_sequence: string; - envelope_xdr: string; - result_xdr: string; - result_meta_xdr: string; - memo: string; - envelope: any; - memo_type: any; - - account: CallFunction; - effects: CallCollectionFunction; - ledger: CallFunction; - operations: CallCollectionFunction; - precedes: CallFunction; - self: CallFunction; - succeeds: CallFunction; -} - -export class AccountCallBuilder extends CallBuilder { - accountId(id: string): this; -} -export class AccountResponse implements AccountRecord { - _links: { [key: string]: { href: string } }; - id: string; - paging_token: string; - account_id: string; - sequence: number; - subentry_count: number; - thresholds: { - low_threshold: number - med_threshold: number - high_threshold: number - }; - flags: { - auth_required: boolean - auth_revocable: boolean - }; - balances: BalanceLine[]; - signers: Array< - { - public_key: string - weight: number - } - >; - data: (options: {value: string}) => Promise<{value: string}>; - data_attr: { - [key: string]: string - }; - inflation_destination?: any; - - effects: CallCollectionFunction; - offers: CallCollectionFunction; - operations: CallCollectionFunction; - payments: CallCollectionFunction; - trades: CallCollectionFunction; - constructor(response: AccountRecord) - accountId(): string; - sequenceNumber(): string; - incrementSequenceNumber(): void; -} - -export class AssetsCallBuilder extends CallBuilder { - forCode(value: string): this; - forIssuer(value: string): this; -} - -export class EffectCallBuilder extends CallBuilder { - forAccount(accountId: string): this; - forLedger(sequence: string): this; - forOperation(operationId: number): this; - forTransaction(transactionId: string): this; -} - -export class LedgerCallBuilder extends CallBuilder { } - -export class OfferCallBuilder extends CallBuilder { } - -export class OperationCallBuilder extends CallBuilder { - forAccount(accountId: string): this; - forLedger(sequence: string): this; - forTransaction(transactionId: string): this; -} -export class OrderbookCallBuilder extends CallBuilder { } -export class PathCallBuilder extends CallBuilder { } -export class PaymentCallBuilder extends CallBuilder { - forAccount(accountId: string): this; - forLedger(sequence: string): this; - forTransaction(transactionId: string): this; -} - -export interface ServerOptions { - allowHttp: boolean; -} - export class Server { - constructor(serverURL: string, options?: ServerOptions) - accounts(): AccountCallBuilder; - assets(): AssetsCallBuilder; - effects(): EffectCallBuilder; - ledgers(): LedgerCallBuilder; - loadAccount(accountId: string): Promise; - offers(resource: string, ...parameters: string[]): OfferCallBuilder; - operations(): OperationCallBuilder; - orderbook(selling: Asset, buying: Asset): OrderbookCallBuilder; + constructor(serverURL: string, options?: Server.ServerOptions) + accounts(): Server.AccountCallBuilder; + assets(): Server.AssetsCallBuilder; + effects(): Server.EffectCallBuilder; + ledgers(): Server.LedgerCallBuilder; + loadAccount(accountId: string): Promise; + offers(resource: string, ...parameters: string[]): Server.OfferCallBuilder; + operations(): Server.OperationCallBuilder; + orderbook(selling: Asset, buying: Asset): Server.OrderbookCallBuilder; paths( source: string, destination: string, destinationAsset: Asset, destinationAmount: string, - ): PathCallBuilder; - payments(): PaymentCallBuilder; - submitTransaction(transaction: Transaction): Promise; + ): Server.PathCallBuilder; + payments(): Server.PaymentCallBuilder; + submitTransaction(transaction: Transaction): Promise; tradeAggregation( base: Asset, counter: Asset, startTime: Date, endTime: Date, resolution: Date, - ): TradeAggregationCallBuilder; - trades(): TradesCallBuilder; - transactions(): TransactionCallBuilder; + ): Server.TradeAggregationCallBuilder; + trades(): Server.TradesCallBuilder; + transactions(): Server.TransactionCallBuilder; serverURL: any; // TODO: require("urijs") } -export class TradeAggregationCallBuilder extends CallBuilder { } -export class TradesCallBuilder extends CallBuilder { - forAssetPair(base: Asset, counter: Asset): this; - forOffer(offerId: string): this; -} +export namespace Server { + class CallBuilder { + constructor(serverUrl: string) + call(): Promise>; + cursor(cursor: string): this; + limit(limit: number | string): this; + order(direction: 'asc' | 'desc'): this; + stream(options?: { onmessage?: (record: T) => void, onerror?: (error: Error) => void }): () => void; + } -export class TransactionCallBuilder extends CallBuilder { - transaction(transactionId: string): this; - forAccount(accountId: string): this; - forLedger(sequence: string | number): this; + interface CollectionPage { + records: T[]; + next: () => Promise>; + prev: () => Promise>; + } + + interface Record { + _links: { + [key: string]: RecordLink + }; + } + + interface RecordLink { + href: string; + templated?: boolean; + } + + /* Due to a bug with the recursive function requests */ + interface CollectionRecord { + _links: { + next: RecordLink + prev: RecordLink + self: RecordLink + }; + _embedded: { + records: T[] + }; + } + + interface CallFunctionTemplateOptions { + cursor?: string | number; + limit?: number; + order?: 'asc' | 'desc'; + } + + type CallFunction = () => Promise; + type CallCollectionFunction = + (options?: CallFunctionTemplateOptions) => Promise>; + + enum ASSET_TYPE { + native = 'native', + credit4 = 'credit_alphanum4', + credit12 = 'credit_alphanum12', + } + + interface BalanceLineNative { + balance: string; + asset_type: ASSET_TYPE.native; + } + interface BalanceLineAsset { + balance: string; + limit: string; + asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; + asset_code: string; + asset_issuer: string; + } + type BalanceLine = BalanceLineNative | BalanceLineAsset; + + interface AccountRecord extends Record { + id: string; + paging_token: string; + account_id: string; + sequence: number; + subentry_count: number; + thresholds: { + low_threshold: number + med_threshold: number + high_threshold: number + }; + flags: { + auth_required: boolean + auth_revocable: boolean + }; + balances: BalanceLine[]; + signers: Array< + { + public_key: string + weight: number + } + >; + data: (options: {value: string}) => Promise<{value: string}>; + data_attr: { + [key: string]: string + }; + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + } + + interface AssetRecord extends Record { + asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; + asset_code: string; + asset_issuer: string; + paging_token: string; + amount: string; + num_accounts: number; + flags: { + auth_required: boolean + auth_revocable: boolean + }; + } + + interface EffectRecord extends Record { + account: string; + paging_token: string; + starting_balance: string; + type_i: string; + type: string; + amount?: any; + + operation?: CallFunction; + precedes?: CallFunction; + succeeds?: CallFunction; + } + + interface LedgerRecord extends Record { + id: string; + paging_token: string; + hash: string; + prev_hash: string; + sequence: number; + transaction_count: number; + operation_count: number; + closed_at: string; + total_coins: string; + fee_pool: string; + base_fee: number; + base_reserve: string; + max_tx_set_size: number; + protocol_version: number; + header_xdr: string; + base_fee_in_stroops: number; + base_reserve_in_stroops: number; + + effects: CallCollectionFunction; + operations: CallCollectionFunction; + self: CallFunction; + transactions: CallCollectionFunction; + } + + interface OfferRecord extends Record { + id: string; + paging_token: string; + seller_attr: string; + selling: Asset; + buying: Asset; + amount: string; + price_r: { numerator: number, denominator: number }; + price: string; + + seller?: CallFunction; + } + + interface BaseOperationRecord extends Record { + id: string; + paging_token: string; + type: string; + type_i: number; + source_account: string; + + self: CallFunction; + succeeds: CallFunction; + precedes: CallFunction; + effects: CallCollectionFunction; + transaction: CallFunction; + } + + interface CreateAccountOperationRecord extends BaseOperationRecord { + type: 'create_account'; + account: string; + funder: string; + starting_balance: string; + } + + interface PaymentOperationRecord extends BaseOperationRecord { + type: 'payment'; + from: string; + to: string; + asset_type: string; + asset_code?: string; + asset_issuer?: string; + amount: string; + + sender: CallFunction; + receiver: CallFunction; + } + + interface PathPaymentOperationRecord extends BaseOperationRecord { + type: 'path_payment'; + from: string; + to: string; + asset_code?: string; + asset_issuer?: string; + asset_type: string; + amount: string; + source_asset_code?: string; + source_asset_issuer?: string; + source_asset_type: string; + source_max: string; + source_amount: string; + } + + interface ManageOfferOperationRecord extends BaseOperationRecord { + type: 'manage_offer'; + offer_id: number; + amount: string; + buying_asset_code?: string; + buying_asset_issuer?: string; + buying_asset_type: string; + price: string; + price_r: { numerator: number, denominator: number }; + selling_asset_code?: string; + selling_asset_issuer?: string; + selling_asset_type: string; + } + + interface PassiveOfferOperationRecord extends BaseOperationRecord { + type: 'create_passive_offer'; + offer_id: number; + amount: string; + buying_asset_code?: string; + buying_asset_issuer?: string; + buying_asset_type: string; + price: string; + price_r: { numerator: number, denominator: number }; + selling_asset_code?: string; + selling_asset_issuer?: string; + selling_asset_type: string; + } + + interface SetOptionsOperationRecord extends BaseOperationRecord { + type: 'set_options'; + signer_key?: string; + signer_weight?: number; + master_key_weight?: number; + low_threshold?: number; + med_threshold?: number; + high_threshold?: number; + home_domain?: string; + set_flags: Array<(1 | 2)>; + set_flags_s: Array<('auth_required_flag' | 'auth_revocable_flag')>; + clear_flags: Array<(1 | 2)>; + clear_flags_s: Array<('auth_required_flag' | 'auth_revocable_flag')>; + } + + interface ChangeTrustOperationRecord extends BaseOperationRecord { + type: 'change_trust'; + asset_code: string; + asset_issuer: string; + asset_type: string; + trustee: string; + trustor: string; + limit: string; + } + + interface AllowTrustOperationRecord extends BaseOperationRecord { + type: 'allow_trust'; + asset_code: string; + asset_issuer: string; + asset_type: string; + authorize: boolean; + trustee: string; + trustor: string; + } + + interface AccountMergeOperationRecord extends BaseOperationRecord { + type: 'account_merge'; + into: string; + } + + interface InflationOperationRecord extends BaseOperationRecord { + type: 'inflation'; + } + + interface ManageDataOperationRecord extends BaseOperationRecord { + type: 'manage_data'; + name: string; + value: string; + } + + interface BumpSequenceOperationRecord extends BaseOperationRecord { + type: 'bump_sequence'; + bump_to: string; + } + + type OperationRecord = CreateAccountOperationRecord + | PaymentOperationRecord + | PathPaymentOperationRecord + | ManageOfferOperationRecord + | PassiveOfferOperationRecord + | SetOptionsOperationRecord + | ChangeTrustOperationRecord + | AllowTrustOperationRecord + | AccountMergeOperationRecord + | InflationOperationRecord + | ManageDataOperationRecord + | BumpSequenceOperationRecord; + + interface OrderbookRecord extends Record { + bids: Array<{ price_r: {}, price: number, amount: string }>; + asks: Array<{ price_r: {}, price: number, amount: string }>; + selling: Asset; + buying: Asset; + } + + interface PaymentPathRecord extends Record { + path: Array<{ + asset_code: string + asset_issuer: string + asset_type: string + }>; + source_amount: string; + source_asset_type: string; + source_asset_code: string; + source_asset_issuer: string; + destination_amount: string; + destination_asset_type: string; + destination_asset_code: string; + destination_asset_issuer: string; + } + + interface TradeRecord extends Record { + id: string; + paging_token: string; + ledger_close_time: string; + base_account: string; + base_amount: string; + base_asset_type: string; + base_asset_code: string; + base_asset_issuer: string; + counter_account: string; + counter_amount: string; + counter_asset_type: string; + counter_asset_code: string; + counter_asset_issuer: string; + base_is_seller: boolean; + + base: CallFunction; + counter: CallFunction; + operation: CallFunction; + } + + interface TradeAggregationRecord extends Record { + timestamp: string; + trade_count: number; + base_volume: string; + counter_volume: string; + avg: string; + high: string; + low: string; + open: string; + close: string; + } + + interface TransactionRecord extends Record { + id: string; + paging_token: string; + hash: string; + ledger_attr: number; + created_at: string; + max_fee: number; + fee_paid: number; + operation_count: number; + result_code: number; + result_code_s: string; + source_account: string; + source_account_sequence: string; + envelope_xdr: string; + result_xdr: string; + result_meta_xdr: string; + memo: string; + envelope: any; + memo_type: any; + + account: CallFunction; + effects: CallCollectionFunction; + ledger: CallFunction; + operations: CallCollectionFunction; + precedes: CallFunction; + self: CallFunction; + succeeds: CallFunction; + } + + class AccountCallBuilder extends CallBuilder { + accountId(id: string): this; + } + class AccountResponse implements AccountRecord { + _links: { [key: string]: { href: string } }; + id: string; + paging_token: string; + account_id: string; + sequence: number; + subentry_count: number; + thresholds: { + low_threshold: number + med_threshold: number + high_threshold: number + }; + flags: { + auth_required: boolean + auth_revocable: boolean + }; + balances: BalanceLine[]; + signers: Array< + { + public_key: string + weight: number + } + >; + data: (options: {value: string}) => Promise<{value: string}>; + data_attr: { + [key: string]: string + }; + inflation_destination?: any; + + effects: CallCollectionFunction; + offers: CallCollectionFunction; + operations: CallCollectionFunction; + payments: CallCollectionFunction; + trades: CallCollectionFunction; + constructor(response: AccountRecord) + accountId(): string; + sequenceNumber(): string; + incrementSequenceNumber(): void; + } + + class AssetsCallBuilder extends CallBuilder { + forCode(value: string): this; + forIssuer(value: string): this; + } + + class EffectCallBuilder extends CallBuilder { + forAccount(accountId: string): this; + forLedger(sequence: string): this; + forOperation(operationId: number): this; + forTransaction(transactionId: string): this; + } + + class LedgerCallBuilder extends CallBuilder { } + + class OfferCallBuilder extends CallBuilder { } + + class OperationCallBuilder extends CallBuilder { + forAccount(accountId: string): this; + forLedger(sequence: string): this; + forTransaction(transactionId: string): this; + } + class OrderbookCallBuilder extends CallBuilder { } + class PathCallBuilder extends CallBuilder { } + class PaymentCallBuilder extends CallBuilder { + forAccount(accountId: string): this; + forLedger(sequence: string): this; + forTransaction(transactionId: string): this; + } + + interface ServerOptions { + allowHttp: boolean; + } + + class TradeAggregationCallBuilder extends CallBuilder { } + class TradesCallBuilder extends CallBuilder { + forAssetPair(base: Asset, counter: Asset): this; + forOffer(offerId: string): this; + } + + class TransactionCallBuilder extends CallBuilder { + transaction(transactionId: string): this; + forAccount(accountId: string): this; + forLedger(sequence: string | number): this; + } } export interface FederationRecord { From 3e4539f9d1d92c8c3575112f7e2165a48db473f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:04:51 +0200 Subject: [PATCH 034/225] fix: *CallBuilder are effectively abstract class --- types/stellar-sdk/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index a8b8317c2d..ff93930fe9 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -484,7 +484,7 @@ export class Server { } export namespace Server { - class CallBuilder { + abstract class CallBuilder { constructor(serverUrl: string) call(): Promise>; cursor(cursor: string): this; @@ -878,7 +878,7 @@ export namespace Server { succeeds: CallFunction; } - class AccountCallBuilder extends CallBuilder { + abstract class AccountCallBuilder extends CallBuilder { accountId(id: string): this; } class AccountResponse implements AccountRecord { @@ -921,30 +921,30 @@ export namespace Server { incrementSequenceNumber(): void; } - class AssetsCallBuilder extends CallBuilder { + abstract class AssetsCallBuilder extends CallBuilder { forCode(value: string): this; forIssuer(value: string): this; } - class EffectCallBuilder extends CallBuilder { + abstract class EffectCallBuilder extends CallBuilder { forAccount(accountId: string): this; forLedger(sequence: string): this; forOperation(operationId: number): this; forTransaction(transactionId: string): this; } - class LedgerCallBuilder extends CallBuilder { } + abstract class LedgerCallBuilder extends CallBuilder { } - class OfferCallBuilder extends CallBuilder { } + abstract class OfferCallBuilder extends CallBuilder { } - class OperationCallBuilder extends CallBuilder { + abstract class OperationCallBuilder extends CallBuilder { forAccount(accountId: string): this; forLedger(sequence: string): this; forTransaction(transactionId: string): this; } - class OrderbookCallBuilder extends CallBuilder { } - class PathCallBuilder extends CallBuilder { } - class PaymentCallBuilder extends CallBuilder { + abstract class OrderbookCallBuilder extends CallBuilder { } + abstract class PathCallBuilder extends CallBuilder { } + abstract class PaymentCallBuilder extends CallBuilder { forAccount(accountId: string): this; forLedger(sequence: string): this; forTransaction(transactionId: string): this; @@ -954,13 +954,13 @@ export namespace Server { allowHttp: boolean; } - class TradeAggregationCallBuilder extends CallBuilder { } - class TradesCallBuilder extends CallBuilder { + abstract class TradeAggregationCallBuilder extends CallBuilder { } + abstract class TradesCallBuilder extends CallBuilder { forAssetPair(base: Asset, counter: Asset): this; forOffer(offerId: string): this; } - class TransactionCallBuilder extends CallBuilder { + abstract class TransactionCallBuilder extends CallBuilder { transaction(transactionId: string): this; forAccount(accountId: string): this; forLedger(sequence: string | number): this; From 72a40070b0bc8b0454458cd83f887162bce97870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:07:42 +0200 Subject: [PATCH 035/225] feat: introduce namespace FederationServer BREAKING CHANGES: Rename interfaces to - `FederationRecord` -> `FederationServer.Record` - `FederationOptions` -> `FederationServer.Options` --- types/stellar-sdk/index.d.ts | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index ff93930fe9..bc1980d37f 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -967,23 +967,25 @@ export namespace Server { } } -export interface FederationRecord { - account_id: string; - memo_type?: string; - memo?: string; -} - -export interface FederationOptions { - allowHttp: boolean; -} export class FederationServer { - static createForDomain(domain: string, options?: FederationOptions): Promise; - static resolve(value: string, options?: FederationOptions): Promise; + static createForDomain(domain: string, options?: FederationServer.Options): Promise; + static resolve(value: string, options?: FederationServer.Options): Promise; - constructor(serverURL: string, domain: string, options?: FederationOptions) - resolveAccountId(account: string): Promise; - resolveAddress(address: string): Promise; - resolveTransactionId(transactionId: string): Promise; + constructor(serverURL: string, domain: string, options?: FederationServer.Options) + resolveAccountId(account: string): Promise; + resolveAddress(address: string): Promise; + resolveTransactionId(transactionId: string): Promise; +} +export namespace FederationServer { + interface Record { + account_id: string; + memo_type?: string; + memo?: string; + } + + interface Options { + allowHttp: boolean; + } } export namespace StellarTomlResolver { From a19c1e5cdad685417c1b841dbee322dfb5875a48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:13:03 +0200 Subject: [PATCH 036/225] fix: ASSET_TYPE --- types/stellar-sdk/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index bc1980d37f..d82fef63dc 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -19,6 +19,11 @@ export namespace StellarBase { incrementSequenceNumber(): void; } + enum ASSET_TYPE { + native = 'native', + credit4 = 'credit_alphanum4', + credit12 = 'credit_alphanum12', + } class Asset { static native(): Asset; static fromOperation(xdr: xdr.Asset): Asset; @@ -414,6 +419,7 @@ export namespace StellarBase { // Re-StellarBase export import Account = StellarBase.Account; +export import ASSET_TYPE = StellarBase.ASSET_TYPE; export import Asset = StellarBase.Asset; export import FastSigning = StellarBase.FastSigning; export import Keypair = StellarBase.Keypair; @@ -532,12 +538,6 @@ export namespace Server { type CallCollectionFunction = (options?: CallFunctionTemplateOptions) => Promise>; - enum ASSET_TYPE { - native = 'native', - credit4 = 'credit_alphanum4', - credit12 = 'credit_alphanum12', - } - interface BalanceLineNative { balance: string; asset_type: ASSET_TYPE.native; From c9af52463510893e54da961da7a0dd7193ba4cb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:38:44 +0200 Subject: [PATCH 037/225] feat: Memo namespace & conditionally typed value BREAKING CHANGES: Requires Typescript 2.8 --- types/stellar-sdk/index.d.ts | 42 ++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d82fef63dc..ec1413af6c 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -7,7 +7,7 @@ // Timur Ramazanov // Kalvis Kalniņš // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /// @@ -69,24 +69,39 @@ export namespace StellarBase { const MemoText = 'text'; const MemoHash = 'hash'; const MemoReturn = 'return'; - type MemoType = typeof MemoNone | typeof MemoID | typeof MemoText | typeof MemoHash | typeof MemoReturn; - class Memo { + type MemoNone = 'none'; + type MemoID = 'id'; + type MemoText = 'text'; + type MemoHash = 'hash'; + type MemoReturn = 'return'; + class Memo { static fromXDRObject(memo: xdr.Memo): Memo; - static hash(hash: string): Memo; - static id(id: string): Memo; - static none(): Memo; - static return(hash: string): Memo; - static text(text: string): Memo; + static hash(hash: string): Memo; + static id(id: string): Memo; + static none(): Memo; + static return(hash: string): Memo; + static text(text: string): Memo; - constructor(type: typeof MemoNone); - constructor(type: typeof MemoID | typeof MemoText | typeof MemoHash | typeof MemoReturn, value: string) - constructor(type: typeof MemoHash | typeof MemoReturn, value: Buffer) + constructor(type: MemoNone, value?: null); + constructor(type: MemoHash | MemoReturn, value: Buffer) + constructor(type: MemoHash | MemoReturn | MemoID | MemoText, value: string) + constructor(type: T, value: Memo.AnyValue) - type: string; - value: null | string | Buffer; + type: T; + value: + T extends MemoNone ? null : + T extends MemoID ? string : + T extends MemoText ? string : + T extends MemoHash ? Buffer : + T extends MemoReturn ? Buffer : + Memo.AnyValue; toXDRObject(): xdr.Memo; } + namespace Memo { + type AnyType = MemoNone | MemoID | MemoText | MemoHash | MemoReturn; + type AnyValue = null | string | Buffer; + } enum Networks { PUBLIC = 'Public Global Stellar Network ; September 2015', @@ -429,7 +444,6 @@ export import MemoID = StellarBase.MemoID; export import MemoNone = StellarBase.MemoNone; export import MemoReturn = StellarBase.MemoReturn; export import MemoText = StellarBase.MemoText; -export import MemoType = StellarBase.MemoType; export import Network = StellarBase.Network; export import Networks = StellarBase.Networks; export import Operation = StellarBase.Operation; From 7577cf4f155f3e856b0de01d957a6542224d7a49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 15:56:23 +0200 Subject: [PATCH 038/225] feat: conditionally typed BalanceLine --- types/stellar-sdk/index.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index ec1413af6c..6041aff0a7 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -556,14 +556,17 @@ export namespace Server { balance: string; asset_type: ASSET_TYPE.native; } - interface BalanceLineAsset { + interface BalanceLineAsset { balance: string; limit: string; - asset_type: ASSET_TYPE.credit4 | ASSET_TYPE.credit12; + asset_type: T; asset_code: string; asset_issuer: string; } - type BalanceLine = BalanceLineNative | BalanceLineAsset; + type BalanceLine = + T extends ASSET_TYPE.native ? BalanceLineNative : + T extends ASSET_TYPE.credit4 | ASSET_TYPE.credit12 ? BalanceLineAsset : + BalanceLineNative | BalanceLineAsset; interface AccountRecord extends Record { id: string; From e261d712fe367c878d0ef9f22bc491647ab37c25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Fri, 28 Dec 2018 16:12:04 +0200 Subject: [PATCH 039/225] test: Memo --- types/stellar-sdk/stellar-sdk-tests.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/types/stellar-sdk/stellar-sdk-tests.ts b/types/stellar-sdk/stellar-sdk-tests.ts index fe72b84a66..bf991b4591 100644 --- a/types/stellar-sdk/stellar-sdk-tests.ts +++ b/types/stellar-sdk/stellar-sdk-tests.ts @@ -12,6 +12,21 @@ transaction; // $ExpectType Transaction StellarSdk.StellarTomlResolver.resolve("example.com", {allowHttp: true, timeout: 100}) .then(toml => toml.FEDERATION_SERVER); -const sig = StellarSdk.xdr.DecoratedSignature.fromXDR(Buffer.of(1, 2)) as StellarSdk.xdr.DecoratedSignature; +const sig = StellarSdk.xdr.DecoratedSignature.fromXDR(Buffer.of(1, 2)); // $ExpectType DecoratedSignature sig.hint(); // $ExpectType Buffer sig.signature(); // $ExpectType Buffer + +StellarSdk.Memo.none(); // $ExpectType Memo<"none"> +StellarSdk.Memo.text('asdf'); // $ExpectType Memo<"text"> +StellarSdk.Memo.id('asdf'); // $ExpectType Memo<"id"> +StellarSdk.Memo.return('asdf'); // $ExpectType Memo<"return"> +StellarSdk.Memo.hash('asdf'); // $ExpectType Memo<"hash"> +StellarSdk.Memo.none().value; // $ExpectType null +StellarSdk.Memo.id('asdf').value; // $ExpectType string +StellarSdk.Memo.text('asdf').value; // $ExpectType string +StellarSdk.Memo.return('asdf').value; // $ExpectType Buffer +StellarSdk.Memo.hash('asdf').value; // $ExpectType Buffer + +// P.S. don't use Memo constructor +(new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf')).value; // $ExpectType AnyValue +(new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf')).type; // $ExpectType AnyType From 2ea29005f89f31ccdae5a30a709651fd16496d32 Mon Sep 17 00:00:00 2001 From: Eric Green Date: Fri, 28 Dec 2018 14:59:16 -0500 Subject: [PATCH 040/225] [sip.js] Library now has its own types --- notNeededPackages.json | 6 + types/sip.js/index.d.ts | 442 ----------------------------------- types/sip.js/sip.js-tests.ts | 105 --------- types/sip.js/tsconfig.json | 24 -- types/sip.js/tslint.json | 6 - 5 files changed, 6 insertions(+), 577 deletions(-) delete mode 100644 types/sip.js/index.d.ts delete mode 100644 types/sip.js/sip.js-tests.ts delete mode 100644 types/sip.js/tsconfig.json delete mode 100644 types/sip.js/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index c64738aa8d..8419526424 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1482,6 +1482,12 @@ "sourceRepoURL": "https://github.com/zeh/simplesignal", "asOfVersion": "1.0.0" }, + { + "libraryName": "sip.js", + "typingsPackageName": "sip.js", + "sourceRepoURL": "https://github.com/onsip/SIP.js", + "asOfVersion": "0.12.0" + }, { "libraryName": "smooth-scrollbar", "typingsPackageName": "smooth-scrollbar", diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts deleted file mode 100644 index 7ca7c2eb98..0000000000 --- a/types/sip.js/index.d.ts +++ /dev/null @@ -1,442 +0,0 @@ -// Type definitions for sip.js 0.9 -// Project: http://sipjs.com -// Definitions by: Kir Dergachev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 - -export as namespace sipjs; - -export class URI { - scheme?: string; - user?: string; - host?: string; - port?: number; - - constructor(scheme?: string, user?: string, host?: string, port?: number, parameters?: string[], headers?: string[]); - static parse(uri: string): sipjs.URI; - - setParam(key: string, value?: string): void; - getParam(key: string): string; - hasParam(key: string): string; - deleteParam(key: string): string; - clearParams(): void; - setHeader(name: string, value: string): void; - getHeader(name: string): string[]; - hasHeader(name: string): boolean; - deleteHeader(name: string): string[]; - clearHeaders(): void; - clone(): URI; - toString(): string; -} - -export namespace UA.EventArgs { - interface ConnectedArgs { attempts: number; } - interface UnregisteredArgs { response: string; cause: string; } - interface RegistrationFailedArgs extends UnregisteredArgs { } -} - -export class UA { - constructor(configuration?: sipjs.ConfigurationParameters); - - start(): UA; - stop(): UA; - register(options?: ExtraHeadersOptions): UA; - unregister(options?: UnregisterOptions): UA; - isRegistered(): boolean; - isConnected(): boolean; - message(target: string | URI, body: string, options?: MessageOptions): Message; - subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; - invite(target: string | URI, element?: InviteOptions | HTMLAudioElement | HTMLVideoElement): Session; - request(method: string, target: string | URI, options?: RequestOptions): ClientContext; - - on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; - on(name: 'disconnected' | 'registered' | string, callback: () => void): void; - on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; - on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; - on(name: 'invite', callback: (session: Session) => void): void; - on(name: 'message', callback: (message: Message) => void): void; -} - -export namespace C { - namespace supported { - const REQUIRED: string; - const SUPPORTED: string; - const UNSUPPORTED: string; - } - - namespace causes { - const INVALID_TARGET: string; - const CONNECTION_ERROR: string; - const REQUEST_TIMEOUT: string; - const SIP_FAILURE_CODE: string; - } -} - -export type DescriptionModifier = (description: RTCSessionDescription) => Promise; - -export interface SessionDescriptionHandler { - peerConnection: any; - - getDescription(options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; - setDescription(sessionDescription: string, options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; - hasDescription: (contentType: string) => boolean; - close: () => void; - holdModifier: (description: RTCSessionDescription) => Promise; - - on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; - on(name: 'userMedia', callback: (stream: MediaStream) => void): void; - on(name: 'userMediaFailed', callback: (error: string) => void): void; - on(name: 'iceCandidate', callback: (candidate: any) => void): void; - on( - name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | - 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, - callback: () => void): void; - on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; - on(name: 'addTrack', callback: (track: any) => void): void; -} - -export interface Session { - startTime?: Date; - endTime?: Date; - ua?: UA; - method?: string; - mediaHandler?: WebRTC.MediaHandler; - request?: IncomingRequest | OutgoingRequest; - localIdentity?: NameAddrHeader; - remoteIdentity?: NameAddrHeader; - assertedIdentity?: NameAddrHeader; - data: ClientContext | ServerContext; - sessionDescriptionHandler: SessionDescriptionHandler; - - dtmf(tone: string | number, options?: Session.DtmfOptions): Session; - terminate(options?: Session.CommonOptions): Session; - bye(options?: Session.CommonOptions): Session; - getLocalStreams(): any[]; - getRemoteStreams(): any[]; - refer(target: string | Session, options?: ExtraHeadersOptions): Session; - mute(options?: ExtraHeadersOptions): void; - unmute(options?: ExtraHeadersOptions): void; - cancel(options?: Session.CommonOptions): void; - progress(options?: Session.ProgressOptions): void; - accept(options?: Session.AcceptOptions): void; - reject(options?: Session.CommonOptions): void; - reply(options?: Session.CommonOptions): void; - hold(options?: Session.HoldOptions): void; - unhold(options?: Session.HoldOptions): void; - isOnHold(): Session.Held; - followRefer(callback: () => void): void; - - on(name: 'progress', callback: (response: IncomingResponse) => void): void; - on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; - on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; - on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel' | 'directionChanged' | 'trackAdded' | 'SessionDescriptionHandler-created' | string, callback: () => void): void; - on(name: 'replaced' | 'reinvite', callback: (newSession: Session) => void): void; - on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; - on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'refer' | 'bye' | 'notify', callback: (request: IncomingRequest) => void): void; - on(name: 'referRequested', callback: (request: ClientContext | ServerContext) => void): void; - - /* these come from the ClientContext that is on the session somehow */ - on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', - callback: (ClientContext: ClientContext) => void): void; -} - -export namespace Session { - interface DtmfOptions extends ExtraHeadersOptions { - duration?: number; - interToneGap?: number; - } - - interface CommonOptions extends ExtraHeadersOptions { - status_code?: number; - reason_phrase?: string; - body?: string; - } - - interface ProgressOptions extends ExtraHeadersOptions { - rel100?: boolean; - media?: MediaConstraints; - } - - interface AcceptOptions { - RTCConstraints?: any; - media?: MediaOptions; - } - - interface HoldOptions extends ExtraHeadersOptions { - eventHandlers?: { - succeeded?(): void; - failed?(): void; - }; - } - - interface DTMF extends Object { - direction: string | 'incoming'; - tone: any; - } - - interface Muted { - audio?: boolean; - video?: boolean; - } - - interface Held { - local: boolean; - remote: boolean; - } -} - -export interface RenderHint { - remote?: Element; - local?: Element; -} - -export interface MediaConstraints { - audio: boolean; - video: boolean; -} - -export interface TurnServer { - urls?: string | string[]; - username?: string; - password?: string; -} - -export namespace WebRTC { - interface Options { - stunServers?: string | string[]; - turnServers?: TurnServer | TurnServer[]; - RTCConstraints?: any; - } - - type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; - - class MediaHandler { - getLocalStreams(): any[]; - getRemoteStreams(): any[]; - render(renderHint: RenderHint): void; - - on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; - on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; - on(name: 'userMediaFailed', callback: (error: string) => void): void; - on(name: 'iceCandidate', callback: (candidate: any) => void): void; - on( - name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | - 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, - callback: () => void): void; - on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; - } - - class Simple { - constructor(options: SimpleConfigurationParameters); - - on(name: 'registered' | 'unregistered', callback: (ua: UA) => void): void; - on(name: 'ringing' | 'connecting' | 'connected' | 'ended', callback: (session: Session) => void): void; - on(name: 'message', callback: (message: Message) => void): void; - - call(target: string | URI): Session; - toggleMute(mute: boolean): void; - hangup: () => Session | void; - } -} - -/* Parameters */ -export interface ConfigurationParameters { - uri?: string; - wsServers?: string | Array; - allowLegacyNotifications?: boolean; - authenticationFactory?: WebRTC.MediaHandlerFactory; - authorizationUser?: string; - autostart?: boolean; - autostop?: boolean; - connectionRecoveryMaxInterval?: number; - connectionRecoveryMinInterval?: number; - contactTransport?: string; - displayName?: string; - extraSupported?: string[]; - forceRport?: boolean; - hackAllowUnregisteredOptionTags?: boolean; - hackCleanJitsiSdpImageattr?: boolean; - hackStripTcp?: boolean; - hackIpInContact?: boolean; - hackViaTcp?: boolean; - hackWssInTransport?: boolean; - iceCheckingTimeout?: number; - instanceId?: string; - keepAliveInterval?: number; - log?: { - builtinEnabled?: boolean; - level?: number | string; - connector?(level: string, category: string, label: string, content: string): void; - }; - mediaHandlerFactory?: WebRTC.MediaHandlerFactory; - noAnswerTimeout?: number; - password?: string; - register?: boolean; - registerExpires?: number; - registrarServer?: string; - rel100?: string; - replaces?: string; - rtcpMuxPolicy?: string; - stunServers?: string | string[]; - traceSip?: boolean; - turnServers?: TurnServer | TurnServer[]; - usePreloadedRoute?: boolean; - userAgentString?: string; - wsServerMaxReconnection?: number; - wsServerReconnectionTimeout?: number; -} - -export interface SimpleConfigurationParameters { - ua: { - wsServers?: string | Array; - uri?: string; - authorizationUser?: string; - password?: string; - displayName?: string; - traceSip?: boolean; - userAgentString?: string; - }; - media?: { - remote?: { - audio?: Element; - video?: Element; - }; - local?: { - audio?: Element; - video?: Element; - }; - }; -} - -export interface SessionDescriptionHandlerParameters { - constraints?: any; - peerConnectionOptions?: { - rtcConfiguration: { - iceServers: TurnServer[]; - iceCheckingTimeout: number; - }; - RTCOfferOptions: {}; - }; -} - -/* Options */ -export interface ExtraHeadersOptions { - extraHeaders?: string[]; -} - -export interface UnregisterOptions extends ExtraHeadersOptions { - all?: boolean; -} - -export interface MessageOptions extends ExtraHeadersOptions { - contentType?: string; -} - -export interface SubscribeOptions extends ExtraHeadersOptions { - expires?: number; -} - -export interface MediaOptions { - constraints?: MediaConstraints; - stream?: any; - render?: RenderHint; -} - -export interface InviteOptions extends ExtraHeadersOptions { - media?: MediaOptions; - anonymous?: boolean; - rel100?: string; - inviteWithoutSdp?: boolean; - RTCConstraints?: any; -} - -export interface RequestOptions extends ExtraHeadersOptions { - body?: string; -} - -/* Contexts */ -export interface Message extends ClientContext { - body: string; -} - -export interface Subscription extends ClientContext { - id: string; - state: string; - event: string; - dialog: string; - timers: {}; - errorCodes: number[]; - subscribe(): Subscription; - unsubscribe(): void; - close(): void; -} - -/* Context */ -export class Context { - ua: UA; - method: string; - request: OutgoingRequest; - localIdentity: NameAddrHeader; - remoteIdentity: NameAddrHeader; - data: {}; -} - -export class ClientContext extends Context { - cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; - - // This exists on all Context, but I cant make it work right - on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'notify', callback: (request: IncomingRequest) => void): void; - on(name: string, callback: () => void): void; - - on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', - callback: (ClientContext: ClientContext) => void): void; -} - -export class ServerContext extends Context { - progress(options?: Session.ProgressOptions): void; - accept(options?: Session.AcceptOptions): void; - reject(options?: Session.CommonOptions): void; - reply(options?: Session.CommonOptions): void; - - // This exists on all Context, but I cant make it work right - on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'notify', callback: (request: IncomingRequest) => void): void; - on(name: string, callback: () => void): void; - - on(name: 'referRequestAccepted' | 'referRequestRejected' | 'referInviteSent' | 'referProgress' | 'referAccepted' | 'referRejected', - callback: (ServerContext: ServerContext) => void): void; -} - -/* Request */ -export interface Request extends Context { -} - -export interface IncomingRequest extends Request { -} - -export interface OutgoingRequest extends Request { -} - -export interface IncomingResponse extends Request { - reason_phrase: string | 'Ringing'; -} - -export interface IncomingMessage extends Request { -} - -/* Header */ -export class NameAddrHeader { - uri: URI; - displayName: string; - - constructor(uri: sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>); - static parse(name_addr_header: string): sipjs.NameAddrHeader; - - setParam(key: string, value?: string): void; - getParam(key: string): string; - deleteParam(key: string): string; - clearParams(): void; -} diff --git a/types/sip.js/sip.js-tests.ts b/types/sip.js/sip.js-tests.ts deleted file mode 100644 index df6d47c7bc..0000000000 --- a/types/sip.js/sip.js-tests.ts +++ /dev/null @@ -1,105 +0,0 @@ -import * as SIP from 'sip.js'; - -let ua: SIP.UA = new SIP.UA(); - -const mediaHandler = (session: SIP.Session, options: SIP.WebRTC.Options) => new SIP.WebRTC.MediaHandler(); -const logConnector = (level: string, category: string, label: string, content: string) => null; - -const uaWithConfig: SIP.UA = new SIP.UA({ - uri: "wss://uri", - wsServers: ["s1", "s2", { ws_uri: "s3", weight: 1 }], - allowLegacyNotifications: true, - authenticationFactory: mediaHandler, - authorizationUser: "user", - autostart: true, - autostop: false, - connectionRecoveryMaxInterval: 1, - connectionRecoveryMinInterval: 1, - displayName: "name", - hackCleanJitsiSdpImageattr: true, - hackStripTcp: true, - hackIpInContact: true, - hackViaTcp: true, - hackWssInTransport: true, - iceCheckingTimeout: 1, - instanceId: "id", - log: { - builtinEnabled: true, - level: 1, - connector: logConnector - }, - mediaHandlerFactory: mediaHandler, - noAnswerTimeout: 1, - password: "", - register: true, - registerExpires: 1, - registrarServer: "sip:registrar.mydomain.com", - rel100: "", - replaces: "", - stunServers: ["", ""], - turnServers: [ - { - password: "", - username: "", - urls: ["", ""] - } - ], - usePreloadedRoute: true, - userAgentString: "", - wsServerMaxReconnection: 1, - wsServerReconnectionTimeout: 1 -}); - -ua.start(); -ua.stop(); - -ua.register(); -ua = ua.register({ extraHeaders: [""] }); - -ua.unregister(); -ua.unregister({ extraHeaders: [""], all: true }); - -const isConnected: boolean = ua.isConnected(); -const isRegistered: boolean = ua.isRegistered(); - -const message: SIP.Message = ua.message("", "", { contentType: "" }); - -ua.subscribe("", "", { expires: 1, extraHeaders: [""] }); -const subscription: SIP.Subscription = ua.subscribe(new SIP.URI(), "", { expires: 1, extraHeaders: [""] }); - -let session = ua.invite("", new HTMLVideoElement()); - -const inviteOptions: SIP.InviteOptions = { - media: { - constraints: { audio: true, video: false }, - stream: new MediaStream(), - render: { remote: new Element(), local: new Element() }, - }, - anonymous: true, - rel100: "", - inviteWithoutSdp: true, - RTCConstraints: {} -}; - -session = ua.invite("", inviteOptions); - -ua.on('connected', (args: SIP.UA.EventArgs.ConnectedArgs) => { }); -ua.on('disconnected', () => { }); -ua.on('registered', () => { }); -ua.on('unregistered', (args: SIP.UA.EventArgs.UnregisteredArgs) => { }); -ua.on('registrationFailed', (args: SIP.UA.EventArgs.RegistrationFailedArgs) => { }); -ua.on('invite', (session: SIP.Session) => { - session.on('progress', (response) => {}); - session.on('accepted', (response) => {}); - session.on('rejected', (response) => {}); -}); -ua.on('message', (message: SIP.Message) => { }); - -session.hold({ - extraHeaders: [""], - eventHandlers: { - succeeded: () => {} - } -}); - -ua.start().stop(); diff --git a/types/sip.js/tsconfig.json b/types/sip.js/tsconfig.json deleted file mode 100644 index ea3b5a009c..0000000000 --- a/types/sip.js/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "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", - "sip.js-tests.ts" - ] -} \ No newline at end of file diff --git a/types/sip.js/tslint.json b/types/sip.js/tslint.json deleted file mode 100644 index 4f44991c3c..0000000000 --- a/types/sip.js/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-empty-interface": false - } -} From c455e25a296d5e23933b9e6445d0b15747eacb63 Mon Sep 17 00:00:00 2001 From: Mattias Martens Date: Fri, 28 Dec 2018 16:33:25 -0800 Subject: [PATCH 041/225] check copy for js-combinatorics --- types/js-combinatorics/index.d.ts | 48 +++++++++++++++---------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/types/js-combinatorics/index.d.ts b/types/js-combinatorics/index.d.ts index 702ef1f9a2..8023aeff73 100644 --- a/types/js-combinatorics/index.d.ts +++ b/types/js-combinatorics/index.d.ts @@ -8,7 +8,7 @@ declare namespace __Combinatorics { interface IGenerator { /** - * Returns the element or undefined if no more element is available. + * Returns the element or undefined if no more elements are available. */ next():T; @@ -18,24 +18,24 @@ declare namespace __Combinatorics { forEach(f:(item:T) => void):void; /** - * All elements at once with function applied to each element. + * Returns an array that is the output of calling the callback function separately on each element. */ map(f:(item:T) => TResult):TResult[]; /** - * Returns an array with elements that passes the filter function. + * Returns an array of elements that return `true` for the filter function. */ filter(predicate:(item:T) => boolean):T[]; /** - * All elements at once. + * Returns an array of all elements. */ toArray():T[]; /** - * Returns the number of elements to be generated which equals to generator.toArray().length - * but it is precalculated without actually generating elements. - * Handy when you prepare for large iteration. + * Returns the total number of elements to be generated. This equals the result of calling + * `generator.toArray().length` but it is precalculated without actually generating any elements. + * Handy when doing setup for a potentially long-running loop. */ length:number; @@ -44,7 +44,7 @@ declare namespace __Combinatorics { interface IPredictableGenerator extends IGenerator { /** - * Returns the nth element (starting 0). + * Returns the nth element (indexed from 0). */ nth(n:number):T; @@ -53,11 +53,10 @@ declare namespace __Combinatorics { interface ICartesianProductGenerator extends IPredictableGenerator { /** - * Arguments are coordinates in integer. - * Arguments can be out of bounds but it returns undefined in such cases. + * Arguments are integer coordinates. + * Arguments can be out of bounds but it returns `undefined` in such cases. */ get(...coordinates:number[]):T; - } /** @@ -76,46 +75,47 @@ declare namespace __Combinatorics { function factorial(n:number):number; /** - * Returns the factoradic representation of n in array, in least significant order. + * Returns the factoradic representation of `n` in an array, in + * least significant order. * See http://en.wikipedia.org/wiki/Factorial_number_system */ function factoradic(n:number):number[]; /** - * Generates the power set of array. + * Generates the power set of `a`. */ function power(a:T[]):IPredictableGenerator; /** - * Generates the combination of array with n elements. - * When n is ommited, the length of the array is used. + * Generates the combination of `a` with `n` elements. + * `n` defaults to the length of `a`. */ function combination(a:T[], n?:number):IGenerator; /** - * Generates the combination of array with n elements, which + * Generates the combination of `a` with `n` elements, which * also supports larger sets of elements. - * When n is ommited, the length of the array is used. - * Somewhat slower than combination() + * When `n` is ommited, the length of the array is used. + * Somewhat slower than `combination()` */ function bigCombination(a:T[], n?:number):IGenerator; /** - * Generates the permutation of array with n elements. - * When n is ommited, the length of the array is used. + * Generates the permutation of `a` with `n` elements. + * `n` defaults to the length of `a`. */ function permutation(a:T[], n?:number):IGenerator; /** - * Generates the permutation of the combination of n. - * Equivalent to permutation(combination(a)), but more efficient. + * Generates the permutation of the combination of `a`. + * Equivalent to `permutation(combination(a))`, but more efficient. */ function permutationCombination(a:T[]):IGenerator; /** - * Generates n-digit "numbers" where each digit is an element in array. + * Generates `n`-digit "numbers" where each digit is an element in array. * Note this "number" is in the least significant order. - * When n is ommited, the length of the array is used. + * `n` defaults to the length of `a`. */ function baseN(a:T[], n?:number):IPredictableGenerator; From e7ed9763dfab6e80d4b4c1410318e1ce69df428e Mon Sep 17 00:00:00 2001 From: Oskar Lindgren Date: Sat, 29 Dec 2018 15:32:38 +0900 Subject: [PATCH 042/225] add webdriverio appium desired capabilities --- types/webdriverio/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/webdriverio/index.d.ts b/types/webdriverio/index.d.ts index 48fb31af47..4a1f585808 100644 --- a/types/webdriverio/index.d.ts +++ b/types/webdriverio/index.d.ts @@ -6,6 +6,7 @@ // Tanvir ul Islam // Dave Parslow // Phil Leger +// Oskar Lindgren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -273,6 +274,11 @@ declare namespace WebdriverIO { [name: string]: any; }; + // Appium specific + platformVersion?: string; + automationName?: string; + app?: string; + cleanSession?: boolean; // Chrome specific From 6ae5225037c41b3ffd3d90dd1e0ede947b932cc9 Mon Sep 17 00:00:00 2001 From: Oskar Lindgren Date: Sat, 29 Dec 2018 15:35:36 +0900 Subject: [PATCH 043/225] refactor webdriverio tests --- types/webdriverio/webdriverio-tests.ts | 162 ++++++++++++++----------- 1 file changed, 89 insertions(+), 73 deletions(-) diff --git a/types/webdriverio/webdriverio-tests.ts b/types/webdriverio/webdriverio-tests.ts index 11b473066b..f5e33e776e 100644 --- a/types/webdriverio/webdriverio-tests.ts +++ b/types/webdriverio/webdriverio-tests.ts @@ -2,11 +2,18 @@ import * as webdriverio from "webdriverio"; import { assert } from "chai"; // Stub mocha functions -const {describe, it, before, after, beforeEach, afterEach} = null as any as { - [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & {only: any, skip: any}; +const { describe, it, before, after, beforeEach, afterEach } = null as any as { + [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & { only: any, skip: any }; }; -describe("webdriver.io page", () => { +describe("my webdriverio tests", () => { + let client: webdriverio.Client; + + before(async () => { + client = webdriverio.remote({ deprecationWarnings: true, desiredCapabilities: { browserName: "phantomjs" } }); + await client.init(); + }); + it("should have the right title - the good old callback way", () => { assert.equal( browser @@ -23,15 +30,6 @@ describe("webdriver.io page", () => { assert.equal(title, "WebdriverIO - Selenium 2.0 javascript bindings for nodejs"); }); }); -}); - -describe.only("my webdriverio tests", () => { - let client: webdriverio.Client; - - before(async () => { - client = webdriverio.remote({ deprecationWarnings: true, desiredCapabilities: { browserName: "phantomjs" } }); - await client.init(); - }); it("Github test", async () => { await client.url("https://github.com/"); @@ -57,76 +55,94 @@ describe.only("my webdriverio tests", () => { }); }); -const matrix = webdriverio.multiremote({ - browserA: { - desiredCapabilities: { - browserName: "chrome", - chromeOptions: { - args: [ - "use-fake-device-for-media-stream", - "use-fake-ui-for-media-stream", - ] - } - } - }, - browserB: { - desiredCapabilities: { - browserName: "chrome", - chromeOptions: { - args: [ - "use-fake-device-for-media-stream", - "use-fake-ui-for-media-stream", - ] - } - } - } +describe("multiremote test", () => { + let matrix: webdriverio.Client; + + before(async () => { + matrix = webdriverio.multiremote({ + browserA: { + desiredCapabilities: { + browserName: "chrome", + chromeOptions: { + args: [ + "use-fake-device-for-media-stream", + "use-fake-ui-for-media-stream", + ], + }, + }, + }, + browserB: { + desiredCapabilities: { + browserName: "chrome", + chromeOptions: { + args: [ + "use-fake-device-for-media-stream", + "use-fake-ui-for-media-stream", + ], + }, + }, + }, + }); }); -const channel = Math.round(Math.random() * 100000000000); + it("clicks a button in a random channel at apprtc", () => { + const channel = Math.round(Math.random() * 100000000000); -matrix - .init() - .url("https://apprtc.appspot.com/r/" + channel) - .click("#confirm-join-button") - .pause(5000) - .end(); + matrix + .init() + .url("https://apprtc.appspot.com/r/" + channel) + .click("#confirm-join-button") + .pause(5000) + .end(); + }); -const options = { - desiredCapabilities: { - browserName: "chrome" - } -}; + after(async () => { + await matrix.end(); + }); +}); -webdriverio - .remote(options) - .init() - .url("https://news.ycombinator.com/") - .selectorExecute("//div", (inputs: HTMLElement[], message: string) => { - return `${inputs.length} ${message}`; - }, "divs on the page") - .then((res: string) => { - console.log(res); - }) - .end(); +describe("testing feaures with chrome", () => { + const options = { + desiredCapabilities: { + browserName: "chrome", + }, + }; -webdriverio - .remote(options) - .init() - .url("http://www.google.com/") - .waitForVisible("//input[@type='submit']", 5000) - .then((visible) => { - console.log(visible); // Should return true - }) - .end(); + it("can use selectorExecute", () => { + webdriverio + .remote(options) + .init() + .url("https://news.ycombinator.com/") + .selectorExecute("//div", (inputs: HTMLElement[], message: string) => { + return `${inputs.length} ${message}`; + }, "divs on the page") + .then((res: string) => { + console.log(res); + }) + .end(); + }); -let hooks: webdriverio.Hooks = {}; + it("can waitForVisible", () => { + webdriverio + .remote(options) + .init() + .url("http://www.google.com/") + .waitForVisible("//input[@type='submit']", 5000) + .then((visible) => { + console.log(visible); // Should return true + }) + .end(); + }); +}); + +let hooks: webdriverio.Hooks = {}; hooks = { - // Hooks can be a noop function - onPrepare: () => undefined, - onError() { - // Hooks don't have to return a value - } + // Hooks can be a noop function + onPrepare: () => undefined, + onError() { + // Hooks don't have to return a value + } }; hooks.onComplete = async () => { From 8414c3f8bea09cdc33d340326f3b4f6b02f8cbd3 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 29 Dec 2018 11:33:05 +0100 Subject: [PATCH 044/225] [retry] Update types to v0.12 --- types/retry/index.d.ts | 176 +++++++++++++++---------------------- types/retry/retry-tests.ts | 45 +++++----- types/retry/tsconfig.json | 4 +- types/retry/tslint.json | 6 +- 4 files changed, 96 insertions(+), 135 deletions(-) diff --git a/types/retry/index.d.ts b/types/retry/index.d.ts index 97729cec2d..543f3e13af 100644 --- a/types/retry/index.d.ts +++ b/types/retry/index.d.ts @@ -1,57 +1,68 @@ -// Type definitions for retry 0.10 +// Type definitions for retry 0.12 // Project: https://github.com/tim-kos/node-retry // Definitions by: Stan Goldmann +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 export interface RetryOperation { - /** - * Defines the function that is to be retried and executes it for the first time right away. - * - * @param callback The function that is to be retried - * @param callback.current Number of attempts callback has been executed so far. - * @param [options.timeout] A timeout in milliseconds. - * @param [options.callback] Callback to execute when the operation takes longer than the timeout. - * - */ - attempt(callback: (current: number) => void, options?: AttemptOptions): void; + /** + * Returns an array of all errors that have been passed to `retryOperation.retry()` so far. + * The returning array has the errors ordered chronologically based on when they were passed to + * `retryOperation.retry()`, which means the first passed error is at index zero and the last is at the last index. + */ + errors(): Error[]; - /** - * Returns false when no error value is given, or the maximum amount of retries has been reached. - * Otherwise it returns true, and retries the operation after the timeout for the current attempt number. - * - * - */ - retry(err?: Error): boolean; + /** + * A reference to the error object that occured most frequently. + * Errors are compared using the `error.message` property. + * If multiple error messages occured the same amount of time, the last error object with that message is returned. + * + * @return If no errors occured so far the value will be `null`. + */ + mainError(): Error | null; - /** - * The number of attempts it took to call the retrying function before it was successful. - * - */ - attempts(): number; + /** + * Defines the function that is to be retried and executes it for the first time right away. + * + * @param fn The function that is to be retried. `currentAttempt` represents the number of attempts + * callback has been executed so far. + * @param [timeoutOps.timeout] A timeout in milliseconds. + * @param [timeoutOps.callback] Callback to execute when the operation takes longer than the timeout. + */ + attempt(fn: (currentAttempt: number) => void, timeoutOps?: AttemptTimeoutOptions): void; - /** - * A reference to the error object that occured most frequently. - * Errors are compared using the error.message property. - * - * @return If no errors occured so far the value will be null. - */ - mainError(): Error | null; + /** + * Returns `false` when no `error` value is given, or the maximum amount of retries has been reached. + * Otherwise it returns `true`, and retries the operation after the timeout for the current attempt number. + */ + retry(err?: Error): boolean; - /** - * Returns an array of all errors that have been passed to RetryOperation.retry() so far. - * - */ - errors(): Error[]; + /** + * Stops the operation being retried. Useful for aborting the operation on a fatal error etc. + */ + stop(): void; - /** - * Stops the operation being retried. Useful for aborting the operation on a fatal error etc. - */ - stop(): void; + /** + * Resets the internal state of the operation object, so that you can call `attempt()` again as if + * this was a new operation object. + */ + reset(): void; + + /** + * Returns an int representing the number of attempts it took to call `fn` before it was successful. + */ + attempts(): number; } -export interface AttemptOptions { +export interface AttemptTimeoutOptions { + /** + * A timeout in milliseconds. + */ timeout?: number; + /** + * Callback to execute when the operation takes longer than the timeout. + */ callback?(): void; } @@ -69,45 +80,33 @@ export interface AttemptOptions { */ export function operation(options?: OperationOptions): RetryOperation; -export interface OperationOptions { +export interface OperationOptions extends TimeoutsOptions { /** - * The maximum amount of times to retry the operation. - * @default 10 - */ - retries?: number; - /** - * The exponential factor to use. - * @default 2 - */ - factor?: number; - /** - * The number of milliseconds before starting the first retry. - * @default 1000 - */ - minTimeout?: number; - /** - * The maximum number of milliseconds between two retries. - * @default Infinity - */ - maxTimeout?: number; - /** - * Randomizes the timeouts by multiplying a factor between 1-2. + * Whether to retry forever. * @default false */ - randomize?: boolean; forever?: boolean; + /** + * Whether to [unref](https://nodejs.org/api/timers.html#timers_unref) the setTimeout's. + * @default false + */ unref?: boolean; + /** + * The maximum time (in milliseconds) that the retried operation is allowed to run. + * @default Infinity + */ + maxRetryTime?: number; } /** Get an array with timeouts and their return values in milliseconds. */ export function timeouts(options?: TimeoutsOptions): number[]; -export interface TimeoutsOptions { +export interface TimeoutsOptions extends CreateTimeoutOptions { + /** + * The maximum amount of times to retry the operation. + * @default 10 + */ retries?: number; - factor?: number; - minTimeout?: number; - maxTimeout?: number; - randomize?: boolean; } /** @@ -148,42 +147,5 @@ export interface CreateTimeoutOptions { * @param methods Methods which need to be wrapped * */ -export function wrap(object: object, options?: WrapOptions, methods?: string[]): void; - -export interface WrapOptions { - /** - * The maximum amount of times to retry the operation. - * @default 10 - */ - retries?: number; - /** - * The exponential factor to use. - * @default 2 - */ - factor?: number; - /** - * The number of milliseconds before starting the first retry. - * @default 1000 - */ - minTimeout?: number; - /** - * The maximum number of milliseconds between two retries. - * @default Infinity - */ - maxTimeout?: number; - /** - * Randomizes the timeouts by multiplying a factor between 1-2. - * @default false - */ - randomize?: boolean; - /** - * Whether to retry forever. - * @default false - */ - forever?: boolean; - /** - * Whether to unref the setTimeout's. - * @default false - */ - unref?: boolean; -} +export function wrap(object: object, methods?: string[]): void; +export function wrap(object: object, options?: OperationOptions, methods?: string[]): void; diff --git a/types/retry/retry-tests.ts b/types/retry/retry-tests.ts index bb5eb35976..a68d6c635a 100644 --- a/types/retry/retry-tests.ts +++ b/types/retry/retry-tests.ts @@ -11,7 +11,7 @@ const evr = false; const unr = false; // Options themselves -const operationOptions = { +const operationOptions: retry.OperationOptions = { retries: ret, factor: fac, minTimeout: min, @@ -19,17 +19,18 @@ const operationOptions = { randomize: rnd, forever: evr, unref: unr, + maxRetryTime: max, }; -const timeoutOptions = { +const timeoutsOptions: retry.TimeoutsOptions = { + retries: ret, factor: fac, minTimeout: min, maxTimeout: max, randomize: rnd, }; -const timeoutsOptions = { - retries: ret, +const createTimeoutOptions: retry.CreateTimeoutOptions = { factor: fac, minTimeout: min, maxTimeout: max, @@ -49,24 +50,26 @@ class Foo { const operation = retry.operation(operationOptions); -operation.attempt((current) => { - const err = Math.random() >= 0.5 ? new Error('Happens to the best of us') : undefined; - - const retry = operation.retry(err); - - if (retry) { - const after = operation.attempts(); - } else { - const errors = operation.errors(); - - const main = operation.mainError(); - } - - operation.stop(); +operation.errors(); // $ExpectType Error[] +operation.mainError(); // $ExpectType Error | null +operation.attempt(current => { + current; // $ExpectType number }); +operation.attempt(current => {}, { timeout: 10 }); +operation.attempt(current => {}, { callback: () => {} }); +operation.retry(); // $ExpectType boolean +operation.retry(new Error()); // $ExpectType boolean +operation.stop(); +operation.reset(); +operation.attempts(); // $ExpectType number -const timeout = retry.createTimeout(att, timeoutOptions); +retry.createTimeout(att); // $ExpectType number +retry.createTimeout(att, createTimeoutOptions); // $ExpectType number -const timeouts = retry.timeouts(timeoutsOptions); +retry.timeouts(); // $ExpectType number[] +retry.timeouts(timeoutsOptions); // $ExpectType number[] -const wrap = retry.wrap(new Foo(), operationOptions, ['bar']); +retry.wrap(new Foo()); +retry.wrap(new Foo(), ['bar']); +retry.wrap(new Foo(), operationOptions, ['bar']); +retry.wrap(new Foo(), operationOptions); diff --git a/types/retry/tsconfig.json b/types/retry/tsconfig.json index 6e2c5d42d2..268dbcfff3 100644 --- a/types/retry/tsconfig.json +++ b/types/retry/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +20,4 @@ "index.d.ts", "retry-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/retry/tslint.json b/types/retry/tslint.json index 26a0c302a8..f93cf8562a 100644 --- a/types/retry/tslint.json +++ b/types/retry/tslint.json @@ -1,7 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-void-expression": false - } + "extends": "dtslint/dt.json" } From 22f5bc8bb7971f4ceef8f98b305679f3bcdd31b1 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 29 Dec 2018 15:22:34 +0100 Subject: [PATCH 045/225] [retry] Fix dependent package --- types/promise-retry/index.d.ts | 6 +++--- types/promise-retry/tsconfig.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/promise-retry/index.d.ts b/types/promise-retry/index.d.ts index f2d9ee5747..01fe6cb25b 100644 --- a/types/promise-retry/index.d.ts +++ b/types/promise-retry/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { WrapOptions } from "retry"; +import { OperationOptions } from "retry"; /** * A function that is retryable, by having implicitly-bound params for both an error handler and an attempt number. * @@ -22,6 +22,6 @@ type RetryableFn = ((retry: (error: any) => never, attempt: numb * @param options The options for how long/often to retry the function for. * @returns The Promise resolved by the input retryableFn, or rejected (if not retried) from its catch block. */ -declare function promiseRetry(retryableFn: RetryableFn, options?: WrapOptions): Promise; -declare function promiseRetry(options: WrapOptions, retryableFn: RetryableFn): Promise; +declare function promiseRetry(retryableFn: RetryableFn, options?: OperationOptions): Promise; +declare function promiseRetry(options: OperationOptions, retryableFn: RetryableFn): Promise; export = promiseRetry; diff --git a/types/promise-retry/tsconfig.json b/types/promise-retry/tsconfig.json index 660e112726..cd598fc1f4 100644 --- a/types/promise-retry/tsconfig.json +++ b/types/promise-retry/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "promise-retry-tests.ts" ] -} \ No newline at end of file +} From 6dc17a08ce2b29b15a63f82fe5069d2143fb2b79 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Sat, 29 Dec 2018 19:15:19 +0200 Subject: [PATCH 046/225] Add React plugin to linkifyjs declaration. --- types/linkifyjs/index.d.ts | 1 + types/linkifyjs/linkifyjs-tests.ts | 260 ++++++++++++++++------------- types/linkifyjs/react.d.ts | 12 ++ 3 files changed, 154 insertions(+), 119 deletions(-) create mode 100644 types/linkifyjs/react.d.ts diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index 9c095a41f3..14f618102b 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for linkifyjs 2.1 // Project: https://github.com/SoapBox/linkifyjs#readme // Definitions by: Sean Zhu +// Ovidiu Bute // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.ts index 5688f9f99f..52d46fb416 100644 --- a/types/linkifyjs/linkifyjs-tests.ts +++ b/types/linkifyjs/linkifyjs-tests.ts @@ -1,141 +1,163 @@ +import * as React from "react"; +import * as ReactDOM from "react-dom"; import linkifyHtml from "linkifyjs/html"; +import Linkify from "linkifyjs/react"; + +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; // From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html -/* attributes */ +describe("linkifyjs/html", () => { + /* attributes */ -linkifyHtml("github.com", { - attributes: { - rel: "nofollow" - } -}); - -/* className */ - -linkifyHtml("github.com", { - className: "new-link--url" -}); - -linkifyHtml("github.com", { - className(href, type) { - return "new-link--" + type; - } -}); - -linkifyHtml("github.com", { - className: { - url: "new-link--url", - email(href: string) { - return "new-link--email"; + linkifyHtml("github.com", { + attributes: { + rel: "nofollow" } - } -}); + }); -/* events */ + /* className */ -linkifyHtml("", { - events: { - click(e) { - alert("Link clicked!"); - }, - mouseover(e) { - alert("Link hovered!"); + linkifyHtml("github.com", { + className: "new-link--url" + }); + + linkifyHtml("github.com", { + className(href, type) { + return "new-link--" + type; } - } -}); + }); -/* defaultProtocol */ - -/* format */ - -linkifyHtml("", { - format(value, type) { - if (type === "url" && value.length > 50) { - value = value.slice(0, 50) + "…"; + linkifyHtml("github.com", { + className: { + url: "new-link--url", + email(href: string) { + return "new-link--email"; + } } - return value; - } -}); + }); -linkifyHtml("", { - format: { - url(value) { - return value.length > 50 ? value.slice(0, 50) + "…" : value; + /* events */ + + linkifyHtml("", { + events: { + click(e) { + alert("Link clicked!"); + }, + mouseover(e) { + alert("Link hovered!"); + } } - } -}); + }); -/* formatHref */ + /* defaultProtocol */ -linkifyHtml("This site is #rad", { - formatHref(href, type) { - if (type === "hashtag") { - href = "https://twitter.com/hashtag/" + href.substring(1); + /* format */ + + linkifyHtml("", { + format(value, type) { + if (type === "url" && value.length > 50) { + value = value.slice(0, 50) + "…"; + } + return value; } - return href; - } -}); + }); -linkifyHtml("Hey @dhh, check out issue #23", { - formatHref: { - mention(href) { - return "https://github.com" + href; - }, - ticket(href) { - return ( - "https://github.com/SoapBox/linkifyjs/issues/" + - href.substring(1) - ); + linkifyHtml("", { + format: { + url(value) { + return value.length > 50 ? value.slice(0, 50) + "…" : value; + } } - } -}); + }); -/* ignoreTags */ + /* formatHref */ -linkifyHtml( - // tslint:disable-next-line:prefer-template - 'Please ignore \n' + - "but do b.ca", - { - ignoreTags: ["script", "style"] - } -); - -/* nl2br */ - -/* tagName */ - -linkifyHtml("github.com", { - tagName: "span" -}); - -linkifyHtml("#swag", { - tagName: { - hashtag: "span" - } -}); - -/* target */ - -linkifyHtml("github.com", { - target: "_parent" -}); - -linkifyHtml("test-email@example.com", { - target: { - url: "_parent", - email: null - } -}); - -/* validate */ - -// Don't linkify links that don't begin in a protocol -// e.g., "http://google.com" will be linkified, but "google.com" will not. -linkifyHtml("www.google.com", { - validate: { - url(value) { - return /^(http|ftp)s?:\/\//.test(value); + linkifyHtml("This site is #rad", { + formatHref(href, type) { + if (type === "hashtag") { + href = "https://twitter.com/hashtag/" + href.substring(1); + } + return href; } - } + }); + + linkifyHtml("Hey @dhh, check out issue #23", { + formatHref: { + mention(href) { + return "https://github.com" + href; + }, + ticket(href) { + return ( + "https://github.com/SoapBox/linkifyjs/issues/" + + href.substring(1) + ); + } + } + }); + + /* ignoreTags */ + + linkifyHtml( + // tslint:disable-next-line:prefer-template + 'Please ignore \n' + + "but do b.ca", + { + ignoreTags: ["script", "style"] + } + ); + + /* nl2br */ + + /* tagName */ + + linkifyHtml("github.com", { + tagName: "span" + }); + + linkifyHtml("#swag", { + tagName: { + hashtag: "span" + } + }); + + /* target */ + + linkifyHtml("github.com", { + target: "_parent" + }); + + linkifyHtml("test-email@example.com", { + target: { + url: "_parent", + email: null + } + }); + + /* validate */ + + // Don't linkify links that don't begin in a protocol + // e.g., "http://google.com" will be linkified, but "google.com" will not. + linkifyHtml("www.google.com", { + validate: { + url(value) { + return /^(http|ftp)s?:\/\//.test(value); + } + } + }); +}); + +describe("linkifyjs/react", () => { + it("should render a Linkify component", () => { + const rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement(Linkify, { + options: { + className: "custom-class-name" + } + }), + rootElement + ); + }); }); diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts new file mode 100644 index 0000000000..352e87bf77 --- /dev/null +++ b/types/linkifyjs/react.d.ts @@ -0,0 +1,12 @@ +import * as React from "react"; +import { LinkifyOptions } from "./index"; + +declare interface LinkifyProps { + options: LinkifyOptions; +} + +declare class Linkify extends React.Component {} + +export { LinkifyProps }; + +export default Linkify; From ff09198a0fecfb2eadd278c92e415396ae61059f Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Sat, 29 Dec 2018 19:19:24 +0200 Subject: [PATCH 047/225] Add new declaration file. --- types/linkifyjs/tsconfig.json | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json index 52b1940fcd..2ddde7ba4f 100644 --- a/types/linkifyjs/tsconfig.json +++ b/types/linkifyjs/tsconfig.json @@ -1,25 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6", "dom"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "html.d.ts", - "linkifyjs-tests.ts" - ] + "files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.ts"] } From 4b21ebf8d887de0592e01e5363f045750939eb83 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Sat, 29 Dec 2018 19:21:56 +0200 Subject: [PATCH 048/225] Change minimum TypeScript version. --- types/linkifyjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index 14f618102b..5626288816 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Sean Zhu // Ovidiu Bute // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 export type PossiblyFuncOfHrefAndType = | T From 3778d7dce48c38b5ff0317bb43e01aec11911e2f Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Sat, 29 Dec 2018 19:27:02 +0200 Subject: [PATCH 049/225] Change minimum TypeScript version. --- types/linkifyjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index 5626288816..d41d7bc8c1 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Sean Zhu // Ovidiu Bute // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 export type PossiblyFuncOfHrefAndType = | T From d6059686990c0007d0c6c5de43e7465e5f122ad7 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Sat, 29 Dec 2018 19:29:46 +0200 Subject: [PATCH 050/225] Remove redundant declare. --- types/linkifyjs/react.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts index 352e87bf77..cdf9d42900 100644 --- a/types/linkifyjs/react.d.ts +++ b/types/linkifyjs/react.d.ts @@ -1,7 +1,7 @@ import * as React from "react"; import { LinkifyOptions } from "./index"; -declare interface LinkifyProps { +interface LinkifyProps { options: LinkifyOptions; } From 92c07e3e6fc463795ec4b5ea288bc553b59389aa Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sat, 29 Dec 2018 20:02:05 +0300 Subject: [PATCH 051/225] [got] Add more hooks to v9 --- types/got/got-tests.ts | 72 ++++++++++++++++++++++++++++++++++++++++++ types/got/index.d.ts | 52 ++++++++++++++++++++++++++---- 2 files changed, 117 insertions(+), 7 deletions(-) diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 1626cae86a..f1f88845d5 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -286,3 +286,75 @@ got('http://todomvc.com', { // Test got.TimeoutError. got('http://todomvc.com', {timeout: 1}).catch((err) => err instanceof got.TimeoutError); + +// Test hooks. +got('example.com', { + hooks: { + beforeRedirect: [ + options => { + if (options.hostname === 'deadSite') { + options.hostname = 'fallbackSite'; + } + } + ] + } +}); +got('example.com', { + hooks: { + beforeRetry: [ + (options, error, retryCount) => { + if (error.statusCode === 413) { // Payload too large + options.body = 'test'; + } + } + ] + } +}); +got('example.com', { + hooks: { + afterResponse: [ + (response, retryWithMergedOptions) => { + if (response.statusCode === 401) { // Unauthorized + const updatedOptions = { + headers: { + token: 'new token' // Refresh the access token + } + }; + + // Make a new retry + return retryWithMergedOptions(updatedOptions); + } + + // No changes otherwise + return response; + } + ] + } +}); +// Test async hooks. +{ + const doSomethingAsync = () => { + throw new Error('unimplemented'); + }; + + got('example.com', { + hooks: { + beforeRedirect: [ + async () => { + await doSomethingAsync(); + } + ], + beforeRetry: [ + async () => { + await doSomethingAsync(); + } + ], + afterResponse: [ + async (response) => { + await doSomethingAsync(); + return response; + } + ] + } + }); +} diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 079e84ff62..0ceb6b945c 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for got 9.2 +// Type definitions for got 9.3 // Project: https://github.com/sindresorhus/got#readme // Definitions by: BendingBender // Linus Unnebäck @@ -102,12 +102,50 @@ declare namespace got { type GotUrl = string | https.RequestOptions | Url | URL; - type Hook = (options: T) => any; - type Hooks = Record<'beforeRequest', Array>>; + /** + * Hooks allow modifications during the request lifecycle. Hook functions may be async and are + * run serially. + * + * @see https://github.com/sindresorhus/got#hooks + * @template Options Request options. + * @template Body Response body type. + */ + interface Hooks { + beforeRequest?: Array>; + beforeRedirect?: Array>; + beforeRetry?: Array>; + afterResponse?: Array>; + } + + /** + * @param options Normalized request options. + */ + type BeforeRequestHook = (options: Options) => any; + + /** + * @param options Normalized request options. + */ + type BeforeRedirectHook = (options: Options) => any; + + /** + * @param options Normalized request options. + * @param error Error from previous attempt. + * @param retryCount Number of retry. + */ + type BeforeRetryHook = (options: Options, error: HTTPError, retryCount: number) => any; + + /** + * @param options Normalized request options. + * @param retryWithMergedOptions Retries request with the updated options. + */ + type AfterResponseHook = ( + response: Response, + retryWithMergedOptions: (updateOptions: Options) => GotPromise + ) => Response | Promise>; interface GotBodyOptions extends GotOptions { body?: string | Buffer | nodeStream.Readable; - hooks?: Hooks>; + hooks?: Hooks, string | Buffer | nodeStream.Readable>; } interface GotJSONOptions extends GotOptions { @@ -115,14 +153,14 @@ declare namespace got { body?: object; form?: boolean; json: true; - hooks?: Hooks; + hooks?: Hooks; } interface GotFormOptions extends GotOptions { - body?: {[key: string]: any}; + body?: Record; form: true; json?: boolean; - hooks?: Hooks>; + hooks?: Hooks, Record>; } interface GotOptions extends InternalRequestOptions { From 1f867d919ef79432ed4e996c34d15b1e3d017abc Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sat, 29 Dec 2018 20:42:03 +0300 Subject: [PATCH 052/225] tests: fix dtslint --- types/got/got-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index f1f88845d5..ff6e2c2dca 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -333,7 +333,7 @@ got('example.com', { }); // Test async hooks. { - const doSomethingAsync = () => { + const doSomethingAsync = (): Promise => { throw new Error('unimplemented'); }; From 7b72165601a8a83f120f5dd4348c6d2a8bd62827 Mon Sep 17 00:00:00 2001 From: Kevin Pennarun Date: Sat, 29 Dec 2018 20:08:04 +0100 Subject: [PATCH 053/225] fix(react-redux)-use-the-new-forwardRef-option --- types/react-redux/index.d.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index bcbcced0bd..39d1a8d743 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -314,6 +314,13 @@ export interface Options boolean; + + /** + * If true, use React's forwardRef to expose a ref of the wrapped component + * + * @default false + */ + forwardRef?: boolean; } /** @@ -383,7 +390,7 @@ export interface ConnectOptions { */ storeKey?: string; /** - * If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. + * @deprecated Use forwardRef * * @default false */ From 7a87b07a44f020fa0130436274afc13c6b04a2cf Mon Sep 17 00:00:00 2001 From: Marcin Date: Sat, 29 Dec 2018 21:44:31 +0100 Subject: [PATCH 054/225] Removed not existing property --- types/johnny-five/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/johnny-five/index.d.ts b/types/johnny-five/index.d.ts index a770cd2126..53716f9b33 100644 --- a/types/johnny-five/index.d.ts +++ b/types/johnny-five/index.d.ts @@ -4,6 +4,7 @@ // Zoltan Ujvary // Simon Colmer // XtrimSystems +// Marcin Obiedziński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -111,11 +112,10 @@ export declare class Board { io: any; id: string; - repl: any; + repl: Repl; isReady: boolean; pins: Array; port: string; - inject: Repl; on(event: string, cb: () => void): this; on(event: "ready", cb: () => void): this; From 575c1ddf6e6311b40d18e8cd2f2412308f1ba878 Mon Sep 17 00:00:00 2001 From: Andres Kalle Date: Sat, 29 Dec 2018 23:55:53 +0200 Subject: [PATCH 055/225] yauzl: added strictFileNames option --- types/yauzl/index.d.ts | 1 + types/yauzl/yauzl-tests.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/types/yauzl/index.d.ts b/types/yauzl/index.d.ts index c0e8b5dc88..11c1849574 100644 --- a/types/yauzl/index.d.ts +++ b/types/yauzl/index.d.ts @@ -83,6 +83,7 @@ export interface Options { lazyEntries?: boolean; decodeStrings?: boolean; validateEntrySizes?: boolean; + strictFileNames?: boolean; } export function open(path: string, options: Options, callback?: (err?: Error, zipfile?: ZipFile) => void): void; diff --git a/types/yauzl/yauzl-tests.ts b/types/yauzl/yauzl-tests.ts index 89dc69df30..a8b2217bee 100644 --- a/types/yauzl/yauzl-tests.ts +++ b/types/yauzl/yauzl-tests.ts @@ -26,3 +26,5 @@ yauzl.open('path/to/file.zip', {lazyEntries: true}, (err, zipfile) => { }); } }); + +yauzl.open('options.zip', {strictFileNames: true}, () => {}); From 38fe08a55f1dcb701f4502643005756c90992ceb Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sun, 30 Dec 2018 04:48:11 +0300 Subject: [PATCH 056/225] fix style --- types/got/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 0ceb6b945c..c0a162331e 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -138,7 +138,7 @@ declare namespace got { * @param options Normalized request options. * @param retryWithMergedOptions Retries request with the updated options. */ - type AfterResponseHook = ( + type AfterResponseHook = ( response: Response, retryWithMergedOptions: (updateOptions: Options) => GotPromise ) => Response | Promise>; From a02c8706a9bed73b442b558da14903d39e8a00f0 Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sun, 30 Dec 2018 05:11:26 +0300 Subject: [PATCH 057/225] fix param doc --- types/got/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/got/index.d.ts b/types/got/index.d.ts index c0a162331e..7635e0255c 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -135,7 +135,7 @@ declare namespace got { type BeforeRetryHook = (options: Options, error: HTTPError, retryCount: number) => any; /** - * @param options Normalized request options. + * @param response Response object. * @param retryWithMergedOptions Retries request with the updated options. */ type AfterResponseHook = ( From 85db6b34af75e9feaae700bd6c436068f1188862 Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sun, 30 Dec 2018 05:20:31 +0300 Subject: [PATCH 058/225] error in beforeRetry hook can be any got error --- types/got/got-tests.ts | 4 ++-- types/got/index.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index ff6e2c2dca..d80d0aadcf 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -303,8 +303,8 @@ got('example.com', { hooks: { beforeRetry: [ (options, error, retryCount) => { - if (error.statusCode === 413) { // Payload too large - options.body = 'test'; + if (error instanceof got.HTTPError && error.statusCode === 413) { // Payload too large + options.body = 'new body'; } } ] diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 7635e0255c..1111258da2 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -132,7 +132,7 @@ declare namespace got { * @param error Error from previous attempt. * @param retryCount Number of retry. */ - type BeforeRetryHook = (options: Options, error: HTTPError, retryCount: number) => any; + type BeforeRetryHook = (options: Options, error: GotError, retryCount: number) => any; /** * @param response Response object. From f65cad9541d3e8f092c6254c3b4bda71ec99ea25 Mon Sep 17 00:00:00 2001 From: ikokostya Date: Sun, 30 Dec 2018 05:31:07 +0300 Subject: [PATCH 059/225] improve param desc for beforeRetryHook --- types/got/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 1111258da2..09b451f4bb 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -129,7 +129,7 @@ declare namespace got { /** * @param options Normalized request options. - * @param error Error from previous attempt. + * @param error Request error. * @param retryCount Number of retry. */ type BeforeRetryHook = (options: Options, error: GotError, retryCount: number) => any; From 33dfeb9d34d7d1973871938222ec7d86ef52546a Mon Sep 17 00:00:00 2001 From: Yongbeen Im Date: Sun, 30 Dec 2018 17:12:38 +0900 Subject: [PATCH 060/225] classnames tsconfig file modified strictNullChecks option to true --- types/classnames/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/classnames/tsconfig.json b/types/classnames/tsconfig.json index f9b03432fc..0e8475e613 100644 --- a/types/classnames/tsconfig.json +++ b/types/classnames/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ From d81e5b3218210620695c15c8aa2a853721c6e1bc Mon Sep 17 00:00:00 2001 From: Yongbeen Im Date: Sun, 30 Dec 2018 17:13:44 +0900 Subject: [PATCH 061/225] calssnames module bind error fixed --- types/classnames/bind.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/classnames/bind.d.ts b/types/classnames/bind.d.ts index 4af94d1835..9befbabd4c 100644 --- a/types/classnames/bind.d.ts +++ b/types/classnames/bind.d.ts @@ -1,3 +1,3 @@ -import * as cn from "./index"; +import classNames = require('./index'); -export function bind(styles: Record): typeof cn; +export function bind(styles: Record): typeof classNames; From fb0afa719b54852c66efedbef76df8c6a04fc99d Mon Sep 17 00:00:00 2001 From: freewind Date: Sun, 30 Dec 2018 21:32:52 +0800 Subject: [PATCH 062/225] superagent: cookie related headers has special types --- types/superagent/index.d.ts | 2 ++ types/superagent/superagent-tests.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 7c1898cdc2..7915277b37 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -100,6 +100,7 @@ declare namespace request { files: any; forbidden: boolean; get(header: string): string; + get(header: 'Set-Cookie'): string[]; header: any; info: boolean; links: object; @@ -148,6 +149,7 @@ declare namespace request { serialize(serializer: Serializer): this; set(field: object): this; set(field: string, val: string): this; + set(field: 'Cookie', val: string[]): this; timeout(ms: number | { deadline?: number, response?: number }): this; type(val: string): this; unset(field: string): this; diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index 44ef7cf773..b261a551d7 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -83,6 +83,12 @@ request .set({ 'API-Key': 'foobar', Accept: 'application/json' }) .end(callback); +// Setting cookie header +request + .get('/search') + .set('Cookie', ['name1=value1; Domain=.test.com; Path=/', 'name2=value2; Domain=.test.com; Path=/']) + .end(callback); + // GET requests request .get('/search') @@ -198,6 +204,12 @@ request('/search') const charset: string = res.charset; }); +// Getting response 'Set-Cookie' +request('/search') + .end((res: request.Response) => { + const setCookie: string[] = res.get('Set-Cookie'); + }); + // Custom parsers request .post('/search') From 31af24a42694a2b2119a7b07320dcb1fc13eec25 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:30:18 +0200 Subject: [PATCH 063/225] Fix interface and add more unit-tests. --- types/linkifyjs/linkifyjs-tests.ts | 48 +++++++++++++++++++++++++----- types/linkifyjs/react.d.ts | 2 +- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.ts index 52d46fb416..12d5b04dbf 100644 --- a/types/linkifyjs/linkifyjs-tests.ts +++ b/types/linkifyjs/linkifyjs-tests.ts @@ -6,9 +6,9 @@ import Linkify from "linkifyjs/react"; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; -// From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html - describe("linkifyjs/html", () => { + // From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html + /* attributes */ linkifyHtml("github.com", { @@ -149,14 +149,48 @@ describe("linkifyjs/html", () => { }); describe("linkifyjs/react", () => { + // From the docs here: https://soapbox.github.io/linkifyjs/docs/linkify-react.html + it("should render a Linkify component", () => { const rootElement = document.createElement("div"); ReactDOM.render( - React.createElement(Linkify, { - options: { - className: "custom-class-name" - } - }), + React.createElement( + Linkify, + {}, + React.createElement("span", "Hello https://google.com") + ), + rootElement + ); + }); + + it("should render a Linkify component with a custom className", () => { + const rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + options: { + className: "custom-class-name" + } + }, + React.createElement("span", "Hello https://google.com") + ), + rootElement + ); + }); + + it("should render a Linkify component with a custom tagName", () => { + const rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + options: { + tagName: "p" + } + }, + React.createElement("span", "Hello https://google.com") + ), rootElement ); }); diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts index cdf9d42900..13591b6a6a 100644 --- a/types/linkifyjs/react.d.ts +++ b/types/linkifyjs/react.d.ts @@ -2,7 +2,7 @@ import * as React from "react"; import { LinkifyOptions } from "./index"; interface LinkifyProps { - options: LinkifyOptions; + options?: LinkifyOptions; } declare class Linkify extends React.Component {} From 3b2f86cb424afcb361b8062aa49246ae624301d3 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:33:02 +0200 Subject: [PATCH 064/225] Remove it calls. --- types/linkifyjs/linkifyjs-tests.ts | 76 ++++++++++++++---------------- 1 file changed, 35 insertions(+), 41 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.ts index 12d5b04dbf..bd7f67ea51 100644 --- a/types/linkifyjs/linkifyjs-tests.ts +++ b/types/linkifyjs/linkifyjs-tests.ts @@ -151,47 +151,41 @@ describe("linkifyjs/html", () => { describe("linkifyjs/react", () => { // From the docs here: https://soapbox.github.io/linkifyjs/docs/linkify-react.html - it("should render a Linkify component", () => { - const rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - {}, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); - }); + let rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + {}, + React.createElement("span", "Hello https://google.com") + ), + rootElement + ); - it("should render a Linkify component with a custom className", () => { - const rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - options: { - className: "custom-class-name" - } - }, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); - }); + rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + options: { + className: "custom-class-name" + } + }, + React.createElement("span", "Hello https://google.com") + ), + rootElement + ); - it("should render a Linkify component with a custom tagName", () => { - const rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - options: { - tagName: "p" - } - }, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); - }); + rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + options: { + tagName: "p" + } + }, + React.createElement("span", "Hello https://google.com") + ), + rootElement + ); }); From 793383d2a415b91273a63aa9c4d94e45957c3659 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:34:21 +0200 Subject: [PATCH 065/225] Simplify export syntax. --- types/linkifyjs/react.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts index 13591b6a6a..ce5dc24896 100644 --- a/types/linkifyjs/react.d.ts +++ b/types/linkifyjs/react.d.ts @@ -1,12 +1,10 @@ import * as React from "react"; import { LinkifyOptions } from "./index"; -interface LinkifyProps { +export interface LinkifyProps { options?: LinkifyOptions; } declare class Linkify extends React.Component {} -export { LinkifyProps }; - export default Linkify; From f687d485ec0acd7df12e15fa95f43ac7671d7ca7 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:38:40 +0200 Subject: [PATCH 066/225] Add missing tagName prop. --- types/linkifyjs/linkifyjs-tests.ts | 5 +---- types/linkifyjs/react.d.ts | 1 + 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.ts index bd7f67ea51..0376960065 100644 --- a/types/linkifyjs/linkifyjs-tests.ts +++ b/types/linkifyjs/linkifyjs-tests.ts @@ -4,7 +4,6 @@ import linkifyHtml from "linkifyjs/html"; import Linkify from "linkifyjs/react"; declare function describe(desc: string, f: () => void): void; -declare function it(desc: string, f: () => void): void; describe("linkifyjs/html", () => { // From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html @@ -180,9 +179,7 @@ describe("linkifyjs/react", () => { React.createElement( Linkify, { - options: { - tagName: "p" - } + tagName: "p" }, React.createElement("span", "Hello https://google.com") ), diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts index ce5dc24896..0631b6c460 100644 --- a/types/linkifyjs/react.d.ts +++ b/types/linkifyjs/react.d.ts @@ -3,6 +3,7 @@ import { LinkifyOptions } from "./index"; export interface LinkifyProps { options?: LinkifyOptions; + tagName?: string; } declare class Linkify extends React.Component {} From 84e169e5bfb182639ce79becc1718fcc129efff4 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:39:50 +0200 Subject: [PATCH 067/225] Rename tests file to tsx. --- types/linkifyjs/{linkifyjs-tests.ts => linkifyjs-tests.tsx} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename types/linkifyjs/{linkifyjs-tests.ts => linkifyjs-tests.tsx} (100%) diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.tsx similarity index 100% rename from types/linkifyjs/linkifyjs-tests.ts rename to types/linkifyjs/linkifyjs-tests.tsx From 396cbe2709b3f7b930a7e5457bec0bb7092cc4e0 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 09:44:43 +0200 Subject: [PATCH 068/225] Fix path to renamed file. --- types/linkifyjs/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json index 2ddde7ba4f..7a19e25d0d 100644 --- a/types/linkifyjs/tsconfig.json +++ b/types/linkifyjs/tsconfig.json @@ -12,5 +12,5 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.ts"] + "files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.tsx"] } From 1845e3f9a525b1a408e1a07e200192659331a334 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 14:31:37 +0200 Subject: [PATCH 069/225] Broaden type for attributes to fix React example. --- types/linkifyjs/index.d.ts | 2 +- types/linkifyjs/linkifyjs-tests.tsx | 40 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index d41d7bc8c1..71f6a59226 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -28,7 +28,7 @@ export interface LinkifyOptions { * (e.g., 'url', 'email', etc.) and returns the object. */ attributes?: PossiblyFuncOfHrefAndType<{ - [attrName: string]: string; + [attrName: string]: any; }> | null; /** diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 0376960065..23b9c1f20e 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -1,5 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; +import { LinkifyOptions } from "linkifyjs"; import linkifyHtml from "linkifyjs/html"; import Linkify from "linkifyjs/react"; @@ -150,7 +151,46 @@ describe("linkifyjs/html", () => { describe("linkifyjs/react", () => { // From the docs here: https://soapbox.github.io/linkifyjs/docs/linkify-react.html + /* Usage */ + + var options: LinkifyOptions = {}; + var content = "For help with GitHub.com, please email support@github.com"; let rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + tagName: "p", + options: options + }, + React.createElement("span", content) + ), + rootElement + ); + + /* Events */ + + let linkProps = { + onClick: (event: any) => { + if (!confirm("Are you sure you want to leave this page?")) { + event.preventDefault(); + } + } + }; + var content = "For help with GitHub.com, please email support@github.com"; + rootElement = document.createElement("div"); + ReactDOM.render( + React.createElement( + Linkify, + { + options: { attributes: linkProps } + }, + React.createElement("span", null) + ), + rootElement + ); + + rootElement = document.createElement("div"); ReactDOM.render( React.createElement( Linkify, From d8e17753b1627df32d8c140c4848c3389543b478 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 14:44:17 +0200 Subject: [PATCH 070/225] Solve linting issue. --- types/linkifyjs/linkifyjs-tests.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 23b9c1f20e..1681932176 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -153,8 +153,8 @@ describe("linkifyjs/react", () => { /* Usage */ - var options: LinkifyOptions = {}; - var content = "For help with GitHub.com, please email support@github.com"; + const options: LinkifyOptions = {}; + const content = "For help with GitHub.com, please email support@github.com"; let rootElement = document.createElement("div"); ReactDOM.render( React.createElement( @@ -170,14 +170,14 @@ describe("linkifyjs/react", () => { /* Events */ - let linkProps = { + const linkProps = { onClick: (event: any) => { if (!confirm("Are you sure you want to leave this page?")) { event.preventDefault(); } } }; - var content = "For help with GitHub.com, please email support@github.com"; + rootElement = document.createElement("div"); ReactDOM.render( React.createElement( From d4b93e7a84a24b58dbe5ad2be56534ed72b50ca4 Mon Sep 17 00:00:00 2001 From: Ashwin Ramaswami Date: Mon, 31 Dec 2018 07:45:58 -0500 Subject: [PATCH 071/225] Add Query.getOptions() --- types/mongoose/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 87ce57f05c..b588b4ecef 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1894,7 +1894,13 @@ declare module "mongoose" { * is an Array. See the examples. */ geometry(object: { type: string, coordinates: any[] }): this; - + + /** + * Returns the current query options as a JSON object. + * @returns current query options + */ + getOptions(): any; + /** * Returns the current query conditions as a JSON object. * @returns current query conditions From 7f01b3fef06e3ffe479629fc5b9c642aa1c006dc Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Mon, 31 Dec 2018 14:46:42 +0200 Subject: [PATCH 072/225] Fix object shorthand linting error. --- types/linkifyjs/linkifyjs-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 1681932176..2ec3979134 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -161,7 +161,7 @@ describe("linkifyjs/react", () => { Linkify, { tagName: "p", - options: options + options }, React.createElement("span", content) ), From 3a7ead14f27e3901b4cd46c9986df7e34981618d Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Mon, 31 Dec 2018 07:23:10 -0700 Subject: [PATCH 073/225] [Opossum] Add Stats and fix symbols. Adds the supporting classes and interfaces for a breaker: Status, Stats, Bucket, Window, and HystrixStats. Fixes a bug with the `timeout` option where `false` was not provided as a valid value. Fixes the attributes of the main `CircuitBreaker` to not be symbols, but instead their correct types. This is a bit confusing when looking at the source of the lib, but while symbols are used extensively, they are not exported or made available via the class. They are only used internally and the classes attributes are exposed via getters. Fixes the global export of `promisify` and `stats` from the module as well as being tacked onto the default exported function. Beefs up the tests by copying examples used in the lib docs. --- types/opossum/index.d.ts | 200 +++++++++++++++++++++++++++------ types/opossum/opossum-tests.ts | 139 +++++++++++++++++------ 2 files changed, 268 insertions(+), 71 deletions(-) diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts index e79a9c4bba..b17a1dd0be 100644 --- a/types/opossum/index.d.ts +++ b/types/opossum/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Quinn Langille // Willy Zhang // Lance Ball +// Matt R. Wilson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -13,63 +14,190 @@ import { EventEmitter } from "events"; export type Action = (...args: any[]) => any; export class CircuitBreaker extends EventEmitter { + constructor(action: Action, options: CircuitBreakerOptions); + + readonly name: string; + readonly group: string; + readonly enabled: boolean; + readonly pendingClose: boolean; + readonly closed: boolean; + readonly opened: boolean; + readonly halfOpen: boolean; + readonly status: Status; + readonly stats: Stats; + readonly hystrixStats: HystrixStats; + readonly warmUp: boolean; + readonly volumeThreshold: number; + clearCache(): void; + open(): void; close(): void; disable(): void; enable(): void; - fallback(func?: (...args: any[]) => any): this; + fallback(func: Action | CircuitBreaker): this; fire(...args: any[]): Promise; - healthCheck(func: (...args: any[]) => Promise, interval?: number): Promise; - on(event: string | symbol, listener: (...args: any[]) => void): this; - open(): void; - promisify(action: Action): Promise; - stats(): stream.Transform; - - static readonly name: symbol; - static readonly group: symbol; - static readonly pendingClose: symbol; - static readonly closed: symbol; - static readonly opened: symbol; - static readonly halfOpen: symbol; - static readonly status: symbol; - static readonly hystrixStats: symbol; - static readonly enabled: symbol; - static readonly warmUp: symbol; - static readonly volumeThreshold: symbol; + healthCheck( + func: (...args: any[]) => Promise, + interval?: number + ): void; } export enum Event { - cacheHit = 'cacheHit', - cacheMiss = 'cacheMiss', - close = 'close', - failure = 'failure', - fallback = 'fallback', - fire = 'fire', - halfOpen = 'halfOpen', - healthCheckFailed = 'health-check-failed', - open = 'open', - reject = 'reject', - semaphoreLocked = 'semaphore-locked', - success = 'success', - timeout = 'timeout' + cacheHit = "cacheHit", + cacheMiss = "cacheMiss", + close = "close", + failure = "failure", + fallback = "fallback", + fire = "fire", + halfOpen = "halfOpen", + healthCheckFailed = "health-check-failed", + open = "open", + reject = "reject", + semaphoreLocked = "semaphore-locked", + success = "success", + timeout = "timeout" } export interface CircuitBreakerOptions { - timeout?: number; + /** + * The time in milliseconds that action should be allowed to execute before timing out. + * Timeout can be disabled by setting this to `false`. + */ + timeout?: number | false; + + /** + * The number of times the circuit can fail before opening. + * @deprecated see options.errorThresholdPercentage + */ maxFailures?: number; + + /** + * The time in milliseconds to wait before setting the breaker to `halfOpen` state, and trying the action again. + */ resetTimeout?: number; + + /** + * Sets the duration of the statistical rolling window, in milliseconds. + * This is how long Opossum keeps metrics for the circuit breaker to use and for publishing. + * @default 10000 + */ rollingCountTimeout?: number; + + /** + * Sets the number of buckets the rolling statistical window is divided into. + * So, if options.rollingCountTimeout is 10,000, and options.rollingCountBuckets is 10, then the + * statistical window will be 1,000 1 second snapshots in the statistical window. + * @default 10 + */ rollingCountBuckets?: number; + + /** + * The circuit name to use when reporting stats. + * Defaults to the name of the action function then falls back to a UUID + */ name?: string; + + /** + * A grouping key for reporting. + * Defaults to the computed value of options.name + */ + group?: string; + + /** + * This property indicates whether execution latencies should be tracked and calculated as percentiles. + * If they are disabled, all summary statistics (mean, percentiles) are returned as -1. + * @default true + */ rollingPercentilesEnabled?: boolean; + + /** + * The number of concurrent requests allowed. + * If the number currently executing function calls is equal to options.capacity, further calls + * to `fire()` are rejected until at least one of the current requests completes. + * @default MAX_SAFE_INTEGER + */ capacity?: number; + + /** + * The error percentage at which to open the circuit and start short-circuiting requests to fallback. + */ errorThresholdPercentage?: number; + + /** + * Whether this circuit is enabled upon construction. + * @default true + */ enabled?: boolean; + + /** + * Determines whether to allow failures without opening the circuit during a brief warmup period + * This can help in situations where no matter what your `errorThresholdPercentage` is, if the + * first execution times out or fails, the circuit immediately opens. + * @default false + */ allowWarmUp?: boolean; + + /** + * The minimum number of requests within the rolling statistical window that must exist before + * the circuit breaker can open. This is similar to `allowWarmUp` in that no matter how many + * failures there are, if the number of requests within the statistical window does not exceed + * this threshold, the circuit will remain closed. + * @default 0 + */ volumeThreshold?: number; + + /** + * If set to true, the value from the first call to `fire` will be cached an subsequent calls + * will not execute the `action` function, but return the cached value instead. + * @default false + */ + cache?: boolean; } -export default function circuitBreaker( - action: Action, - options?: CircuitBreakerOptions -): CircuitBreaker; +export interface Status extends EventEmitter { + stats: Stats; + window: Window; + + increment(property: string, latencyRunTime?: number): void; + open(): void; + close(): void; +} + +export interface Bucket { + failures: number; + fallbacks: number; + successes: number; + rejects: number; + fires: number; + timeouts: number; + cacheHits: number; + cacheMisses: number; + semaphoreRejections: number; + percentiles: { [percentile: number]: number }; + latencyTimes: number[]; +} + +export type Window = Bucket[]; + +export interface Stats extends Bucket { + latencyMean: number; +} + +export class HystrixStats { + constructor(circuit: CircuitBreaker); + + getHystrixStream(): stream.Transform; +} + +export function promisify(action: Action): (...args: any[]) => Promise; +export const stats: stream.Transform; + +interface index { + (action: Action, options: CircuitBreakerOptions): CircuitBreaker; + + promisify: (action: Action) => (...args: any[]) => Promise; + stats: stream.Transform; +} + +export const circuitBreaker: index; +export default circuitBreaker; diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts index 9ec5425416..ebbf0bea47 100644 --- a/types/opossum/opossum-tests.ts +++ b/types/opossum/opossum-tests.ts @@ -1,48 +1,117 @@ -import { Transform } from "stream"; -import circuitBreaker, { CircuitBreaker, CircuitBreakerOptions } from "opossum"; +import * as fs from "fs"; +import circuitBreaker, { + CircuitBreaker, + CircuitBreakerOptions, + promisify, + stats, + Stats, + Window +} from "opossum"; -const _blank = () => {}; -const async_blank = () => new Promise(resolve => null); +let readFile = promisify(fs.readFile); +stats.removeAllListeners(); -const testNoOptions: CircuitBreaker = circuitBreaker(_blank); +let breaker: CircuitBreaker; +const callbackNoArgs = () => console.log("foo"); -const options: CircuitBreakerOptions = { - timeout: 1, - maxFailures: 1, - resetTimeout: 1, - rollingCountTimeout: 1, - rollingCountBuckets: 1, - name: "testing", +breaker = circuitBreaker(() => true, { + timeout: false, + maxFailures: 50, + resetTimeout: 10, + rollingCountTimeout: 500, + rollingCountBuckets: 20, + name: "test", + group: "group", rollingPercentilesEnabled: true, capacity: 1, errorThresholdPercentage: 1, enabled: true, allowWarmUp: true, - volumeThreshold: 1 + volumeThreshold: 1, + cache: true +}); + +breaker.name; // $ExpectType string +breaker.group; // $ExpectType string +breaker.enabled; // $ExpectType boolean +breaker.pendingClose; // $ExpectType boolean +breaker.closed; // $ExpectType boolean +breaker.opened; // $ExpectType boolean +breaker.halfOpen; // $ExpectType boolean +breaker.warmUp; // $ExpectType boolean +breaker.volumeThreshold; // $ExpectType number +breaker.status.stats.latencyMean; // $ExpectType number +breaker.stats.latencyTimes; // $ExpectType number[] +breaker.hystrixStats.getHystrixStream().removeAllListeners(); + +breaker.clearCache(); // $ExpectType void +breaker.open(); // $ExpectType void +breaker.close(); // $ExpectType void +breaker.disable(); // $ExpectType void +breaker.enable(); // $ExpectType void + +// The following are examples are from the libs README and official documentation +// https://nodeshift.github.io/opossum/index.html. + +function asyncFunctionThatCouldFail(x: any, y: any) { + return new Promise((resolve, reject) => { + // Do something, maybe on the network or a disk + resolve([x, y]); + }); +} + +const options: CircuitBreakerOptions = { + timeout: 3000, // If our function takes longer than 3 seconds, trigger a failure + errorThresholdPercentage: 50, // When 50% of requests fail, trip the circuit + resetTimeout: 30000 // After 30 seconds, try again. }; +breaker = circuitBreaker(asyncFunctionThatCouldFail, options); -const testWithOptions: CircuitBreaker = circuitBreaker(_blank, options); -const shouldBeAPromise: Promise = testWithOptions.promisify(_blank); -const shouldBeATransformStream: Transform = testWithOptions.stats(); +breaker + .fire("foo") + .then(console.log) + .catch(console.error); -const healthCheck: Promise = testWithOptions.healthCheck(async_blank, 8); -const shouldBeACircuitBreaker: CircuitBreaker = testWithOptions.fallback(); -const shouldBeAPromiseGeneric: Promise = testWithOptions.fire(); +breaker = circuitBreaker(asyncFunctionThatCouldFail, options); +// if asyncFunctionThatCouldFail starts to fail, firing the breaker +// will trigger our fallback function +breaker.fallback(() => "Sorry, out of service right now"); +breaker.on("fallback", result => console.log(result)); -const shouldBeVoid = (): void => testWithOptions.enable(); -const shouldBeVoid2 = (): void => testWithOptions.disable(); -const shouldBeVoid3 = (): void => testWithOptions.close(); -const shouldBeVoid4 = (): void => testWithOptions.open(); -const shouldBeVoid5 = (): void => testWithOptions.clearCache(); +breaker = circuitBreaker(callbackNoArgs, options); -const shouldBeSymbol: symbol = CircuitBreaker.name; -const shouldBeSymbol2: symbol = CircuitBreaker.group; -const shouldBeSymbol3: symbol = CircuitBreaker.pendingClose; -const shouldBeSymbol4: symbol = CircuitBreaker.closed; -const shouldBeSymbol5: symbol = CircuitBreaker.opened; -const shouldBeSymbol6: symbol = CircuitBreaker.halfOpen; -const shouldBeSymbol7: symbol = CircuitBreaker.hystrixStats; -const shouldBeSymbol8: symbol = CircuitBreaker.status; -const shouldBeSymbol9: symbol = CircuitBreaker.enabled; -const shouldBeSymbol10: symbol = CircuitBreaker.warmUp; -const shouldBeSymbol11: symbol = CircuitBreaker.volumeThreshold; +breaker.fallback(callbackNoArgs); + +breaker.on("success", result => console.log(result)); +breaker.on("timeout", callbackNoArgs); +breaker.on("reject", callbackNoArgs); +breaker.on("open", callbackNoArgs); +breaker.on("halfOpen", callbackNoArgs); +breaker.on("close", callbackNoArgs); +breaker.on("fallback", data => console.log(data)); + +readFile = circuitBreaker.promisify(fs.readFile); +breaker = circuitBreaker(readFile, options); + +breaker + .fire("./package.json", "utf-8") + .then(console.log) + .catch(console.error); + +breaker = circuitBreaker(fs.readFile, {}); + +breaker.hystrixStats.getHystrixStream().pipe(process.stdout); + +// Creates a 1 second window consisting of ten time slices, +// each 100ms long. +const circuit = circuitBreaker(fs.readFile, { + rollingCountBuckets: 10, + rollingCountTimeout: 1000 +}); + +// get the cumulative statistics for the last second +const theStats: Stats = breaker.status.stats; + +// get the array of 10, 1 second time slices for the last second +const window: Window = breaker.status.window; +window[0].fires; // $ExpectType number From fa697d0de0e6527d1a82710644caeeb405e67526 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 23 Dec 2018 21:06:10 +0100 Subject: [PATCH 074/225] [@keyv/mysql] Add types --- types/keyv__mysql/index.d.ts | 33 ++++++++++++++++++++++++++ types/keyv__mysql/keyv__mysql-tests.ts | 12 ++++++++++ types/keyv__mysql/tsconfig.json | 28 ++++++++++++++++++++++ types/keyv__mysql/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100644 types/keyv__mysql/index.d.ts create mode 100644 types/keyv__mysql/keyv__mysql-tests.ts create mode 100644 types/keyv__mysql/tsconfig.json create mode 100644 types/keyv__mysql/tslint.json diff --git a/types/keyv__mysql/index.d.ts b/types/keyv__mysql/index.d.ts new file mode 100644 index 0000000000..4aef9d06e0 --- /dev/null +++ b/types/keyv__mysql/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for @keyv/mysql 1.1 +// Project: https://github.com/lukechilds/keyv-mysql +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { EventEmitter } from 'events'; + +export = KeyvMysql; + +declare class KeyvMysql extends EventEmitter implements Store { + readonly ttlSupport: false; + namespace?: string; + + constructor(uri?: string); + constructor(options?: KeyvMysql.Options); // tslint:disable-line:unified-signatures + + get(key: string): Promise; + set(key: string, value: string | undefined): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvMysql { + interface Options { + uri?: string; + table?: string; + keySize?: number; + } +} diff --git a/types/keyv__mysql/keyv__mysql-tests.ts b/types/keyv__mysql/keyv__mysql-tests.ts new file mode 100644 index 0000000000..5a1947710d --- /dev/null +++ b/types/keyv__mysql/keyv__mysql-tests.ts @@ -0,0 +1,12 @@ +import Keyv = require('keyv'); +import KeyvMysql = require('@keyv/mysql'); + +new Keyv('mysql://user:pass@localhost:3306/dbname', { table: 'cache' }); + +new KeyvMysql('mysql://user:pass@localhost:3306/dbname'); +new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); +new KeyvMysql({ table: 'cache' }); +new KeyvMysql({ keySize: 100 }); + +const mysql = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); +new Keyv({ store: mysql }); diff --git a/types/keyv__mysql/tsconfig.json b/types/keyv__mysql/tsconfig.json new file mode 100644 index 0000000000..e50e632d7c --- /dev/null +++ b/types/keyv__mysql/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/mysql": [ + "keyv__mysql" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__mysql-tests.ts" + ] +} diff --git a/types/keyv__mysql/tslint.json b/types/keyv__mysql/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__mysql/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2b98b72dad31181b1dc87d6456490a93ec1f1714 Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 31 Dec 2018 13:42:51 -0800 Subject: [PATCH 075/225] types for treeify --- types/treeify/index.d.ts | 28 ++++++++++++++++++++++++++++ types/treeify/treeify-tests.ts | 31 +++++++++++++++++++++++++++++++ types/treeify/tsconfig.json | 16 ++++++++++++++++ types/treeify/tslint.json | 4 ++++ 4 files changed, 79 insertions(+) create mode 100644 types/treeify/index.d.ts create mode 100644 types/treeify/treeify-tests.ts create mode 100644 types/treeify/tsconfig.json create mode 100644 types/treeify/tslint.json diff --git a/types/treeify/index.d.ts b/types/treeify/index.d.ts new file mode 100644 index 0000000000..29375cf7ba --- /dev/null +++ b/types/treeify/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for tress 1.0 +// Project: https://github.com/notatestuser/treeify +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export interface TreeObject { + [k: string]: TreeValue; +} +export type TreeValue = string | TreeObject; + +export function asTree( + treeObj: TreeObject, + showValues: boolean, + hideFunctions: boolean +): string; + +export function asLines( + treeObj: TreeObject, + showValues: boolean, + lineCallback: (line: string) => void +): string; +export function asLines( + treeObj: TreeObject, + showValues: boolean, + hideFunctions: boolean, + lineCallback: (line: string) => void +): string; diff --git a/types/treeify/treeify-tests.ts b/types/treeify/treeify-tests.ts new file mode 100644 index 0000000000..75d3de92a2 --- /dev/null +++ b/types/treeify/treeify-tests.ts @@ -0,0 +1,31 @@ +import * as treeify from 'treeify'; + +function log(s: string): void {} + +treeify.asTree( + { + apples: 'gala', // ├─ apples: gala + oranges: 'mandarin' // └─ oranges: mandarin + }, + true, + true +); + +treeify.asLines( + { + apples: 'gala', // ├─ apples: gala + oranges: 'mandarin' // └─ oranges: mandarin + }, + true, + log +); + +treeify.asLines( + { + apples: 'gala', // ├─ apples: gala + oranges: 'mandarin' // └─ oranges: mandarin + }, + true, + false, + log +); diff --git a/types/treeify/tsconfig.json b/types/treeify/tsconfig.json new file mode 100644 index 0000000000..965d33c826 --- /dev/null +++ b/types/treeify/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [] + }, + "files": ["index.d.ts", "treeify-tests.ts"] +} diff --git a/types/treeify/tslint.json b/types/treeify/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/treeify/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} From 15a42cb90767d65bed9c7a10a1e5a8515cae9286 Mon Sep 17 00:00:00 2001 From: Rishi Sharma <5098873+rthreei@users.noreply.github.com> Date: Mon, 31 Dec 2018 16:49:43 -0500 Subject: [PATCH 076/225] Adds ensure to API interface --- types/xmlpoke/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/xmlpoke/index.d.ts b/types/xmlpoke/index.d.ts index d8566d4364..68bde4f9ab 100644 --- a/types/xmlpoke/index.d.ts +++ b/types/xmlpoke/index.d.ts @@ -25,6 +25,7 @@ declare module XmlPoke { // ghost module withBasePath(xpath: string): API; addNamespace(prefix: string, uri: string): API; errorOnNoMatches(): API; + ensure(xpath: string): API; } interface CDataValue { value: string; From a85ec9001a6a77c53fe59f84aa7b4a1a3fb0580e Mon Sep 17 00:00:00 2001 From: Rishi Sharma <5098873+rthreei@users.noreply.github.com> Date: Mon, 31 Dec 2018 16:54:26 -0500 Subject: [PATCH 077/225] Add a test --- types/xmlpoke/xmlpoke-tests.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/xmlpoke/xmlpoke-tests.ts b/types/xmlpoke/xmlpoke-tests.ts index 1079d19756..04cab2aa1f 100644 --- a/types/xmlpoke/xmlpoke-tests.ts +++ b/types/xmlpoke/xmlpoke-tests.ts @@ -76,3 +76,7 @@ result = xmlpoke('', xml => return 'y'; })); assert.equal(result, 'y'); + +// ensure +result = xmlpoke('', xml => xml.ensure('a/b')); +assert.equal(result, ''); From f1b04d0c9aade73ec41d6957ac15e64ced8c93af Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 31 Dec 2018 14:30:46 -0800 Subject: [PATCH 078/225] nested data test case --- types/treeify/treeify-tests.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/types/treeify/treeify-tests.ts b/types/treeify/treeify-tests.ts index 75d3de92a2..b8132ec0cf 100644 --- a/types/treeify/treeify-tests.ts +++ b/types/treeify/treeify-tests.ts @@ -4,7 +4,7 @@ function log(s: string): void {} treeify.asTree( { - apples: 'gala', // ├─ apples: gala + apples: 'gala', // ├─ apples: gala oranges: 'mandarin' // └─ oranges: mandarin }, true, @@ -13,8 +13,12 @@ treeify.asTree( treeify.asLines( { - apples: 'gala', // ├─ apples: gala - oranges: 'mandarin' // └─ oranges: mandarin + apples: 'gala', // ├─ apples: gala + oranges: 'mandarin', // ├─ oranges: mandarin + grapes: { // └─ grapes + seedless: 'Thompson, Selma Pete', // ├─ seedless: Thompson, Selma Pete + seeded: 'concord' // └─ seeded: Concord + } }, true, log @@ -22,7 +26,7 @@ treeify.asLines( treeify.asLines( { - apples: 'gala', // ├─ apples: gala + apples: 'gala', // ├─ apples: gala oranges: 'mandarin' // └─ oranges: mandarin }, true, From b5bb7b09f84bffe6a229f0349c4565c717ba6656 Mon Sep 17 00:00:00 2001 From: Ivan Ha Date: Tue, 1 Jan 2019 09:51:17 +0800 Subject: [PATCH 079/225] [randomcolor] support for setting hue from a hex color --- types/randomcolor/index.d.ts | 4 ++-- types/randomcolor/randomcolor-tests.ts | 14 +++++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/types/randomcolor/index.d.ts b/types/randomcolor/index.d.ts index 8a95bf6d65..d0d36297b8 100644 --- a/types/randomcolor/index.d.ts +++ b/types/randomcolor/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for randomColor 0.5.0 +// Type definitions for randomColor 0.5.2 // Project: https://github.com/davidmerfield/randomColor // Definitions by: Mathias Feitzinger , Brady Liles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ declare function randomColor(options?: RandomColorOptions): string; interface RandomColorOptions { - hue?: number | "red" | "orange" | "yellow" | "green" | "blue" | "purple" | "pink" | "monochrome" | "random"; + hue?: number | string; luminosity?: "bright" | "light" | "dark" | "random"; count?: number; seed?: number | string; diff --git a/types/randomcolor/randomcolor-tests.ts b/types/randomcolor/randomcolor-tests.ts index 5bd36b7eb4..595ea0781f 100644 --- a/types/randomcolor/randomcolor-tests.ts +++ b/types/randomcolor/randomcolor-tests.ts @@ -35,4 +35,16 @@ randomColor({ randomColor({ luminosity: 'light', format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' -}); \ No newline at end of file +}); + +// Returns a dark RGB color with specified alpha +randomColor({ + luminosity: 'dark', + format: 'rgba', + alpha: 0.5 // e.g. 'rgba(9, 1, 107, 0.5)', +}); + +// Support for setting hue from a hex color +randomColor({ + hue: "#00FFFF" +}); From db92425c03e131bd52307806f1b32e36974c7967 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Tue, 1 Jan 2019 09:12:24 +0200 Subject: [PATCH 080/225] Use a narrower type. --- types/linkifyjs/index.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index 71f6a59226..a036ab52c1 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -5,6 +5,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +import * as React from "react"; + export type PossiblyFuncOfHrefAndType = | T | ((href: string, type: string) => T); @@ -27,9 +29,9 @@ export interface LinkifyOptions { * Also accepts a function that takes the unformatted href, the link type * (e.g., 'url', 'email', etc.) and returns the object. */ - attributes?: PossiblyFuncOfHrefAndType<{ - [attrName: string]: any; - }> | null; + attributes?: PossiblyFuncOfHrefAndType< + React.AnchorHTMLAttributes + > | null; /** * className From 84c8a9d2d9276669bb107c83a1732872bb286332 Mon Sep 17 00:00:00 2001 From: Daniel Ostrovsky Date: Tue, 1 Jan 2019 11:51:19 +0200 Subject: [PATCH 081/225] [pubnub] Added "history" method with following interfaces: HistoryParameters, HistoryMessage, HistoryResponse, HistoryStatus --- types/pubnub/index.d.ts | 41 +++++++++++++++++++++++++++++++++++- types/pubnub/pubnub-tests.ts | 5 +++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 257ca3cd44..c10cd506b9 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr +// Definitions by: bitbankinc , +// rollymaduk , +// vitosamson , +// FlorianDr , +// danduh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration // TypeScript Version: 2.2 @@ -42,6 +46,11 @@ declare class Pubnub { params: Pubnub.FireParameters ): Promise; + history( + params: Pubnub.HistoryParameters, + callback: (status: Pubnub.HistoryStatus, response: Pubnub.HistoryResponse) => void + ): void; + subscribe(params: Pubnub.SubscribeParameters): void; unsubscribe(params: Pubnub.UnsubscribeParameters): void; @@ -193,6 +202,34 @@ declare namespace Pubnub { timetoken: number; } + interface HistoryParameters { + channel: string; + count: number; + stringifiedTimeToken?: boolean; + includeTimetoken?: boolean; + reverse?: boolean; + start?: number; // timetoken + end?: number; // timetoken + } + + interface HistoryMessage { + entry: any; + timetoken?: string | number; + } + + interface HistoryResponse { + endTimeToken?: number; + startTimeToken?: number; + messages: HistoryMessage[]; + } + + interface HistoryStatus { + error: boolean; + errorData?: Error; + operation: string; // see Pubnub.Operations + statusCode?: number; + } + interface PublishStatus { operation: string; // see Pubnub.Operations category: string; // see Pubnub.Categories; @@ -225,7 +262,9 @@ declare namespace Pubnub { // addListener interface ListenerParameters { status?(statusEvent: StatusEvent): void; + message?(messageEvent: MessageEvent): void; + presence?(presenceEvent: PresenceEvent): void; } diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 50660bd942..96dd4202ba 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -87,6 +87,11 @@ pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); +pubnub.history({channel: 'channel-1', count: 2}, (status, res) => { + console.log(status); + console.log(res); +}); + const cryptoOptions = { encryptKey: true, keyEncoding: 'utf8', From a051a8341db5f319eb3d4fb661a6dcd898859087 Mon Sep 17 00:00:00 2001 From: Hamed Baatour Date: Tue, 1 Jan 2019 15:41:27 +0300 Subject: [PATCH 082/225] types(showdown): add missing showdown types for v1.9.0 --- types/showdown/index.d.ts | 70 ++++++++++++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 8 deletions(-) diff --git a/types/showdown/index.d.ts b/types/showdown/index.d.ts index 21075fd6c7..df2f17ab52 100644 --- a/types/showdown/index.d.ts +++ b/types/showdown/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Showdown 1.9.0 -// Project: https://github.com/coreyti/showdown -// Definitions by: cbowdon , Pei-Tang Huang , Ariel-Saldana +// Project: https://github.com/showdownjs/showdown +// Definitions by: Hamed Baatour, cbowdon , Pei-Tang Huang , Ariel-Saldana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = Showdown; @@ -64,6 +64,10 @@ declare namespace Showdown { output: ShowdownExtension[]; } + interface Metadata { + [meta: string]: string; + } + interface ShowdownOptions { /** * Omit the trailing newline in a code block. Ex: @@ -279,6 +283,43 @@ declare namespace Showdown { * @default false */ backslashEscapesHTMLTags?: boolean; + + /** + * Enable emoji support. Ex: `this is a :smile: emoji. + * + * @default false + */ + emoji?: boolean; + + /** + * Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, + * underscores no longer parses into `` and `` + * + * @default false + */ + underline?: boolean; + + /** + * Outputs a complete html document, including ``, `` and `` tags + * + * @default false + */ + completeHTMLDocument?: boolean; + + /** + * Outputs a complete html document, including ``, `` and `` tags + * + * @default false + */ + metadata?: boolean; + + /** + * Split adjacent blockquote blocks + * + * @default false + */ + splitAdjacentBlockquotes?: boolean; + } @@ -296,11 +337,11 @@ declare namespace Showdown { /** * Converts an HTML string into a markdown string - * - * @param src The input text (HTML) - * @returns The output markdown + * @param src + * @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used. + * @returns {string} */ - makeMarkdown(src: string): string; + makeMarkdown(src: string, HTMLParser?: any): string; /** * Setting a "local" option only affects the specified Converter object. @@ -360,7 +401,20 @@ declare namespace Showdown { * * @param flavor name */ - setFlavor(name: string): void; + setFlavor(name: 'github' | 'original' | 'ghost' | 'vanilla' | 'allOn'): void; + + /** + * Get the metadata of the previously parsed document + * @param raw + * @returns {string|{}} + */ + getMetadata(raw?: boolean): string | Metadata + + /** + * Get the metadata format of the previously parsed document + * @returns {string} + */ + getMetadataFormat(): string; } @@ -477,5 +531,5 @@ declare namespace Showdown { * * @param name */ - function setFlavor(name: string): void; + function setFlavor(name: 'github' | 'original' | 'ghost' | 'vanilla' | 'allOn'): void; } From 36fa54b6d15414e50c362bee7e1c07dfa98f5253 Mon Sep 17 00:00:00 2001 From: Hamed Baatour Date: Tue, 1 Jan 2019 16:31:52 +0300 Subject: [PATCH 083/225] types(showdown): fix header authors format --- types/showdown/index.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/showdown/index.d.ts b/types/showdown/index.d.ts index df2f17ab52..c0f3134f77 100644 --- a/types/showdown/index.d.ts +++ b/types/showdown/index.d.ts @@ -1,6 +1,9 @@ -// Type definitions for Showdown 1.9.0 +// Type definitions for Showdown 1.9. // Project: https://github.com/showdownjs/showdown -// Definitions by: Hamed Baatour, cbowdon , Pei-Tang Huang , Ariel-Saldana +// Definitions by: Hamed Baatour , +// cbowdon , +// Pei-Tang Huang , +// Ariel-Saldana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = Showdown; From a270ca9e8570b70a8a0f083071600e46c573730f Mon Sep 17 00:00:00 2001 From: Hamed Baatour Date: Tue, 1 Jan 2019 16:49:42 +0300 Subject: [PATCH 084/225] types(showdown): fix missing version patch number --- types/showdown/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/showdown/index.d.ts b/types/showdown/index.d.ts index c0f3134f77..c058591d91 100644 --- a/types/showdown/index.d.ts +++ b/types/showdown/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Showdown 1.9. +// Type definitions for Showdown 1.9.0 // Project: https://github.com/showdownjs/showdown // Definitions by: Hamed Baatour , // cbowdon , From 1e77f45f8fd9a00c336290d2b618dee5d4495aa0 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 1 Jan 2019 14:58:16 +0100 Subject: [PATCH 085/225] [urix] Add types --- types/urix/index.d.ts | 8 ++++++++ types/urix/tsconfig.json | 23 +++++++++++++++++++++++ types/urix/tslint.json | 1 + types/urix/urix-tests.ts | 3 +++ 4 files changed, 35 insertions(+) create mode 100644 types/urix/index.d.ts create mode 100644 types/urix/tsconfig.json create mode 100644 types/urix/tslint.json create mode 100644 types/urix/urix-tests.ts diff --git a/types/urix/index.d.ts b/types/urix/index.d.ts new file mode 100644 index 0000000000..480e9f55e4 --- /dev/null +++ b/types/urix/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for urix 0.1 +// Project: https://github.com/lydell/urix +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = urix; + +declare function urix(path: string): string; diff --git a/types/urix/tsconfig.json b/types/urix/tsconfig.json new file mode 100644 index 0000000000..d461c52533 --- /dev/null +++ b/types/urix/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", + "urix-tests.ts" + ] +} diff --git a/types/urix/tslint.json b/types/urix/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/urix/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/urix/urix-tests.ts b/types/urix/urix-tests.ts new file mode 100644 index 0000000000..3c8df8fc5e --- /dev/null +++ b/types/urix/urix-tests.ts @@ -0,0 +1,3 @@ +import urix = require('urix'); + +urix('c:\\users\\you\\foo'); // $ExpectType string From 2d9e9d30e3c2d625f817b213552a0bc7ee1df8f6 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 1 Jan 2019 15:17:57 +0100 Subject: [PATCH 086/225] [pretty-hrtime] Add types --- types/pretty-hrtime/index.d.ts | 15 ++++++++++++++ types/pretty-hrtime/pretty-hrtime-tests.ts | 9 +++++++++ types/pretty-hrtime/tsconfig.json | 23 ++++++++++++++++++++++ types/pretty-hrtime/tslint.json | 1 + 4 files changed, 48 insertions(+) create mode 100644 types/pretty-hrtime/index.d.ts create mode 100644 types/pretty-hrtime/pretty-hrtime-tests.ts create mode 100644 types/pretty-hrtime/tsconfig.json create mode 100644 types/pretty-hrtime/tslint.json diff --git a/types/pretty-hrtime/index.d.ts b/types/pretty-hrtime/index.d.ts new file mode 100644 index 0000000000..af7016500e --- /dev/null +++ b/types/pretty-hrtime/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for pretty-hrtime 1.0 +// Project: https://github.com/robrich/pretty-hrtime +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = prettyHrtime; + +declare function prettyHrtime(hrTime: [number, number], options?: prettyHrtime.Options): string; + +declare namespace prettyHrtime { + interface Options { + verbose?: boolean; + precise?: boolean; + } +} diff --git a/types/pretty-hrtime/pretty-hrtime-tests.ts b/types/pretty-hrtime/pretty-hrtime-tests.ts new file mode 100644 index 0000000000..3da4cc242f --- /dev/null +++ b/types/pretty-hrtime/pretty-hrtime-tests.ts @@ -0,0 +1,9 @@ +/// + +import prettyHrtime = require('pretty-hrtime'); + +const hrtime = process.hrtime(); + +prettyHrtime(hrtime); // $ExpectType string +prettyHrtime(hrtime, { verbose: true }); // $ExpectType string +prettyHrtime(hrtime, { precise: true }); // $ExpectType string diff --git a/types/pretty-hrtime/tsconfig.json b/types/pretty-hrtime/tsconfig.json new file mode 100644 index 0000000000..f24583f376 --- /dev/null +++ b/types/pretty-hrtime/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", + "pretty-hrtime-tests.ts" + ] +} diff --git a/types/pretty-hrtime/tslint.json b/types/pretty-hrtime/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pretty-hrtime/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 570db36e68c88373e141c53fbcb9d7a45ddd550d Mon Sep 17 00:00:00 2001 From: spacejack Date: Tue, 1 Jan 2019 17:51:48 -0500 Subject: [PATCH 087/225] Edits to pass new linting rules --- types/mithril/index.d.ts | 12 ++++++------ types/mithril/test/test-api.ts | 8 ++++---- types/mithril/test/test-route.ts | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 32f3976e2e..be2b03f298 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -173,7 +173,7 @@ declare namespace Mithril { type ChildArrayOrPrimitive = ChildArray | string | number | boolean; /** Virtual DOM nodes, or vnodes, are Javascript objects that represent an element (or parts of the DOM). */ - interface Vnode = Lifecycle> { + interface Vnode = {}> { /** The nodeName of a DOM element. It may also be the string [ if a vnode is a fragment, # if it's a text vnode, or < if it's a trusted HTML vnode. Additionally, it may be a component. */ tag: string | ComponentTypes; /** A hashmap of DOM attributes, events, properties and lifecycle methods. */ @@ -194,7 +194,7 @@ declare namespace Mithril { // In some lifecycle methods, Vnode will have a dom property // and possibly a domSize property. - interface VnodeDOM = Lifecycle> extends Vnode { + interface VnodeDOM = {}> extends Vnode { /** Points to the element that corresponds to the vnode. */ dom: Element; /** This defines the number of DOM elements that the vnode represents (starting from the element referenced by the dom property). */ @@ -210,7 +210,7 @@ declare namespace Mithril { * Any Javascript object that has a view method can be used as a Mithril component. * Components can be consumed via the m() utility. */ - interface Component = Lifecycle> extends Lifecycle { + interface Component = {}> extends Lifecycle { /** Creates a view out of virtual elements. */ view(this: State, vnode: Vnode): Children | null | void; } @@ -242,16 +242,16 @@ declare namespace Mithril { * Any function that returns an object with a view method can be used as a Mithril component. * Components can be consumed via the m() utility. */ - type FactoryComponent = (vnode: Vnode) => Component; + type FactoryComponent = (vnode: Vnode) => Component; /** * Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. * Any Javascript object that has a view method is a Mithril component. Components can be consumed via the m() utility. */ - type Comp = Lifecycle> = Component & State; + type Comp = {}> = Component & State; /** Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. Components can be consumed via the m() utility. */ - type ComponentTypes = Lifecycle> = Component | { new (vnode: CVnode): ClassComponent } | FactoryComponent; + type ComponentTypes = {}> = Component | { new (vnode: CVnode): ClassComponent } | FactoryComponent; /** This represents the attributes available for configuring virtual elements, beyond the applicable DOM attributes. */ interface Attributes extends Lifecycle { diff --git a/types/mithril/test/test-api.ts b/types/mithril/test/test-api.ts index 73e03edeae..a8a042a891 100644 --- a/types/mithril/test/test-api.ts +++ b/types/mithril/test/test-api.ts @@ -116,7 +116,7 @@ const FRAME_BUDGET = 100; { // define a component - const Greeter: m.Comp<{ style: string }, {}> = { + const Greeter: m.Comp<{ style: string }> = { view(vnode) { return m("div", vnode.attrs, ["Hello ", vnode.children]); } @@ -191,7 +191,7 @@ const FRAME_BUDGET = 100; //////////////////////////////////////////////////////////////////////////////// { - const Fader: m.Comp<{}, {}> = { + const Fader: m.Comp = { onbeforeremove(vnode) { vnode.dom.classList.add("fade-out"); return new Promise(resolve => { @@ -227,7 +227,7 @@ const FRAME_BUDGET = 100; } }; - const Form: m.Comp<{term: string}, {}> = { + const Form: m.Comp<{term: string}> = { oninit(vnode) { state.term = vnode.attrs.term || ""; // populated from the `history.state` property if the user presses the back button }, @@ -239,7 +239,7 @@ const FRAME_BUDGET = 100; } }; - const Layout: m.Comp<{}, {}> = { + const Layout: m.Comp = { view(vnode) { return m(".layout", vnode.children); } diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 7f82c9fa40..030a260bcb 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -89,7 +89,7 @@ route(document.body, '/', { test4: { onmatch(args, path) { // Must provide a Promise type if we want type checking - return new Promise>((resolve, reject) => { + return new Promise>((resolve, reject) => { resolve(component2); }); } From 80d3201a48fb41e96ecbd58246815132de68d2de Mon Sep 17 00:00:00 2001 From: Slobodan Kletnikov Date: Wed, 2 Jan 2019 00:00:10 +0100 Subject: [PATCH 088/225] Add UncontrolledCarousel type --- types/reactstrap/index.d.ts | 7 +++++-- types/reactstrap/lib/Carousel.d.ts | 20 ++++++++++++++++++++ types/reactstrap/lib/Uncontrolled.d.ts | 3 +++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index 8197cf5bb1..d2779b4ab6 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -241,17 +241,20 @@ import { UncontrolledButtonDropdown as UncontrolledButtonDropdown_, UncontrolledDropdown as UncontrolledDropdown_, UncontrolledTooltip as UncontrolledTooltip_, - UncontrolledCollapse as UncontrolledCollapse_ + UncontrolledCollapse as UncontrolledCollapse_, + UncontrolledCarousel as UncontrolledCarousel_ } from './lib/Uncontrolled'; export class UncontrolledAlert extends UncontrolledAlert_ {} export class UncontrolledButtonDropdown extends UncontrolledButtonDropdown_ {} export class UncontrolledDropdown extends UncontrolledDropdown_ {} export class UncontrolledTooltip extends UncontrolledTooltip_ {} export class UncontrolledCollapse extends UncontrolledCollapse_ {} +export class UncontrolledCarousel extends UncontrolledCarousel_ {} export { UncontrolledButtonDropdownProps, UncontrolledAlertProps, UncontrolledDropdownProps, UncontrolledTooltipProps, - UncontrolledCollapseProps + UncontrolledCollapseProps, + UncontrolledCarouselProps } from './lib/Uncontrolled'; diff --git a/types/reactstrap/lib/Carousel.d.ts b/types/reactstrap/lib/Carousel.d.ts index 0f59105f77..69899eff34 100644 --- a/types/reactstrap/lib/Carousel.d.ts +++ b/types/reactstrap/lib/Carousel.d.ts @@ -15,5 +15,25 @@ export type CarouselProps = React.HTMLProps & { cssModule?: CSSModule } & T; +export type UncontrolledProps = React.HTMLProps & { + items: any[]; + activeIndex?: number; + next?: () => void; + previous?: () => void; + keyboard?: boolean; + pause?: "hover" | false; + ride?: "carousel"; + interval?: number | string | boolean; + mouseEnter?: () => void; + mouseExit?: () => void; + slide?: boolean; + cssModule?: CSSModule; + controls?: boolean; + indicators?: boolean; + autoPlay?: boolean; +} & T; + +export type UncontrolledCarouselProps = UncontrolledProps; + declare class Carousel extends React.Component> {} export default Carousel; diff --git a/types/reactstrap/lib/Uncontrolled.d.ts b/types/reactstrap/lib/Uncontrolled.d.ts index 118b76d0d1..3be770852f 100644 --- a/types/reactstrap/lib/Uncontrolled.d.ts +++ b/types/reactstrap/lib/Uncontrolled.d.ts @@ -5,15 +5,18 @@ import { UncontrolledButtonDropdownProps } from './ButtonDropdown'; import { UncontrolledDropdownProps } from './Dropdown'; import { UncontrolledTooltipProps } from './Tooltip'; import { UncontrolledCollapseProps } from './Collapse'; +import { UncontrolledCarouselProps } from "./Carousel"; export class UncontrolledAlert extends React.Component> {} export class UncontrolledButtonDropdown extends React.Component> {} export class UncontrolledDropdown extends React.Component> {} export class UncontrolledTooltip extends React.Component> {} export class UncontrolledCollapse extends React.Component> {} +export class UncontrolledCarousel extends React.Component> {} export { UncontrolledAlertProps } from './Alert'; export { UncontrolledButtonDropdownProps } from './ButtonDropdown'; export { UncontrolledDropdownProps } from './Dropdown'; export { UncontrolledTooltipProps } from './Tooltip'; export { UncontrolledCollapseProps } from './Collapse'; +export { UncontrolledCarouselProps } from "./Carousel"; From f516c9be01c554eb2e0fe6c0c0ff94dc9c7ca32e Mon Sep 17 00:00:00 2001 From: spacejack Date: Tue, 1 Jan 2019 18:04:14 -0500 Subject: [PATCH 089/225] Add ClosureComponent type --- types/mithril/index.d.ts | 7 ++++ types/mithril/test/test-factory-component.ts | 38 ++++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index be2b03f298..83de8c9825 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -244,6 +244,13 @@ declare namespace Mithril { */ type FactoryComponent = (vnode: Vnode) => Component; + /** + * Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. + * Any function that returns an object with a view method can be used as a Mithril component. + * Components can be consumed via the m() utility. + */ + type ClosureComponent = FactoryComponent; + /** * Components are a mechanism to encapsulate parts of a view to make code easier to organize and/or reuse. * Any Javascript object that has a view method is a Mithril component. Components can be consumed via the m() utility. diff --git a/types/mithril/test/test-factory-component.ts b/types/mithril/test/test-factory-component.ts index 6d0102fe38..b0d8f3b265 100644 --- a/types/mithril/test/test-factory-component.ts +++ b/types/mithril/test/test-factory-component.ts @@ -1,5 +1,5 @@ -import m = require('mithril'); -import { Component, FactoryComponent, Vnode } from 'mithril'; +import * as m from 'mithril'; +import { Component, ClosureComponent, FactoryComponent } from 'mithril'; /////////////////////////////////////////////////////////// // 0. @@ -50,6 +50,13 @@ const comp2: FactoryComponent = vnode => ({ // vnode is inferred } }); +// 2a. Test ClosureComponent type alias +const comp2a: ClosureComponent = vnode => ({ // vnode is inferred + view({attrs: {title, description}}) { // Comp2Attrs type is inferred + return [m('h2', title), m('p', description)]; + } +}); + /////////////////////////////////////////////////////////// // 3. // Declares attrs type inline. @@ -80,6 +87,31 @@ const comp3: FactoryComponent<{pageHead: string}> = () => ({ } }); +// 3.a Test ClosureComponent type alias +const comp3a: ClosureComponent<{pageHead: string}> = () => ({ + oncreate({dom}) { + // Can do stuff with dom + }, + view({attrs}) { + return m('.page', + m('h1', attrs.pageHead), + m(comp2, + { + // attrs is type checked - nice! + title: "A Title", + description: "Some descriptive text.", + onremove(vnode) { + console.log("comp2 was removed"); + }, + } + ), + // Test other hyperscript parameter variations + m(comp1, m(comp1)), + m('br') + ); + } +}); + /////////////////////////////////////////////////////////// // 4. // Stateful component using closure method & var @@ -152,7 +184,9 @@ m.route(document.body, '/', { '/comp0': comp0, '/comp1': comp1, '/comp2': comp2, + '/comp2a': comp2a, '/comp3': comp3, + '/comp3a': comp3a, '/comp4': comp4, '/comp5': comp5 }); From b9256feb46be0b27b5a304690a8db0d37d6bcb2d Mon Sep 17 00:00:00 2001 From: Slobodan Kletnikov Date: Wed, 2 Jan 2019 00:16:18 +0100 Subject: [PATCH 090/225] Add UncontrolledCarousel test --- types/reactstrap/reactstrap-tests.tsx | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 427c5ae19e..4c6d1a98db 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -75,6 +75,7 @@ import { UncontrolledDropdown, UncontrolledTooltip, UncontrolledCollapse, + UncontrolledCarousel, TabContent, Table, Tag, @@ -4297,3 +4298,28 @@ function Example123() {
); } + +function Example124() { + // https://reactstrap.github.io/components/carousel/ + const items = [ + { + src: 'data:image/svg+xml...', + altText: 'Slide 1', + caption: 'Slide 1' + }, + { + src: 'data:image/svg+xml...', + altText: 'Slide 2', + caption: 'Slide 2' + }, + { + src: 'data:image/svg+xml...', + altText: 'Slide 3', + caption: 'Slide 3' + } + ]; + + return ( + + ); +} From f35e50837d12ad8035ba0886ee75fd1976deab2a Mon Sep 17 00:00:00 2001 From: nossbigg Date: Mon, 31 Dec 2018 10:43:55 +0800 Subject: [PATCH 091/225] Add test ID-related props to react-native-datepicker --- types/react-native-datepicker/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index dd69061311..c86b52b80d 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-native-datepicker 1.6 // Project: https://github.com/xgfe/react-native-datepicker // Definitions by: Jacob Baskin +// Cheng Gibson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -37,6 +38,9 @@ export interface DatePickerProps { minuteInterval?: number; TouchableComponent?: React.Component; locale?: string; + testID?: string; + cancelBtnTestID?: string; + confirmBtnTestID?: string; } declare class DatePicker extends React.Component { From 95d043358d9ec7b1668de0abac97497ab404ff04 Mon Sep 17 00:00:00 2001 From: nossbigg Date: Tue, 1 Jan 2019 19:26:03 +0800 Subject: [PATCH 092/225] Enhance styling props for react-native-datepicker --- types/react-native-datepicker/index.d.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index c86b52b80d..b2cbdbcc83 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -6,9 +6,24 @@ // TypeScript Version: 2.8 import * as React from 'react'; -import { ImageURISource } from 'react-native'; +import { StyleProp, TextStyle, ImageStyle, ViewStyle, ImageURISource } from 'react-native'; import * as moment from 'moment'; +interface CustomStylesProps { + placeholderText?: StyleProp; + dateText?: StyleProp; + dateIcon?: StyleProp; + dateInput?: StyleProp; + dateTouchBody?: StyleProp; + datePickerCon?: StyleProp; + datePicker?: StyleProp; + btnCancel?: StyleProp; + btnTextCancel?: StyleProp; + btnConfirm?: StyleProp; + btnTextConfirm?: StyleProp; + disabled?: StyleProp; +} + export interface DatePickerProps { mode?: 'date' | 'datetime' | 'time'; androidMode?: 'default' | 'calendar' | 'spinner'; @@ -33,8 +48,8 @@ export interface DatePickerProps { modalOnResponderTerminationRequest?(e: any): boolean; is24Hour?: boolean; getDateStr?: (date: Date) => string; - style?: any; - customStyles?: any; + style?: StyleProp; + customStyles?: CustomStylesProps; minuteInterval?: number; TouchableComponent?: React.Component; locale?: string; From 96f25c1d3a8f1786c454d38f33fa61826f74246a Mon Sep 17 00:00:00 2001 From: nossbigg Date: Wed, 2 Jan 2019 10:57:40 +0800 Subject: [PATCH 093/225] Add missing props for react-native-datepicker --- types/react-native-datepicker/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index b2cbdbcc83..ec7ac67b8d 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -52,7 +52,9 @@ export interface DatePickerProps { customStyles?: CustomStylesProps; minuteInterval?: number; TouchableComponent?: React.Component; + allowFontScaling?: boolean; locale?: string; + timeZoneOffsetInMinutes?: number; testID?: string; cancelBtnTestID?: string; confirmBtnTestID?: string; From f33738893dc8e4f35a4cae51c5dadbeabd3fad86 Mon Sep 17 00:00:00 2001 From: nossbigg Date: Wed, 2 Jan 2019 10:58:09 +0800 Subject: [PATCH 094/225] Bump version to 1.7 for react-native-datepicker --- types/react-native-datepicker/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index ec7ac67b8d..35adb46730 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-datepicker 1.6 +// Type definitions for react-native-datepicker 1.7 // Project: https://github.com/xgfe/react-native-datepicker // Definitions by: Jacob Baskin // Cheng Gibson From c302245a91ebe1e37a957318215b6ccaf3f0577c Mon Sep 17 00:00:00 2001 From: nossbigg Date: Wed, 2 Jan 2019 11:09:43 +0800 Subject: [PATCH 095/225] Export CustomStyles for react-native-datepicker --- types/react-native-datepicker/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index 35adb46730..63d20c9a6b 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -9,7 +9,7 @@ import * as React from 'react'; import { StyleProp, TextStyle, ImageStyle, ViewStyle, ImageURISource } from 'react-native'; import * as moment from 'moment'; -interface CustomStylesProps { +export interface DatePickerCustomStylesProps { placeholderText?: StyleProp; dateText?: StyleProp; dateIcon?: StyleProp; @@ -49,7 +49,7 @@ export interface DatePickerProps { is24Hour?: boolean; getDateStr?: (date: Date) => string; style?: StyleProp; - customStyles?: CustomStylesProps; + customStyles?: DatePickerCustomStylesProps; minuteInterval?: number; TouchableComponent?: React.Component; allowFontScaling?: boolean; From 0e62835aeacfe8262d1d985a8bfc8c45a1c617c1 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 1 Jan 2019 23:32:00 -0500 Subject: [PATCH 096/225] Add types for raf --- types/raf/index.d.ts | 12 ++++++++++++ types/raf/raf-tests.ts | 11 +++++++++++ types/raf/tsconfig.json | 23 +++++++++++++++++++++++ types/raf/tslint.json | 3 +++ 4 files changed, 49 insertions(+) create mode 100644 types/raf/index.d.ts create mode 100644 types/raf/raf-tests.ts create mode 100644 types/raf/tsconfig.json create mode 100644 types/raf/tslint.json diff --git a/types/raf/index.d.ts b/types/raf/index.d.ts new file mode 100644 index 0000000000..ef7d214811 --- /dev/null +++ b/types/raf/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for raf 3.4.0 +// Project: https://github.com/chrisdickinson/raf#readme +// Definitions by: Ben Lorantfy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const raf: { + (callback: (timestamp: number) => void): number; + cancel: (handle: number) => void; + polyfill: (globalObject?: any) => void; +} + +export default raf; diff --git a/types/raf/raf-tests.ts b/types/raf/raf-tests.ts new file mode 100644 index 0000000000..d57019913d --- /dev/null +++ b/types/raf/raf-tests.ts @@ -0,0 +1,11 @@ +import raf from "raf"; + +const handle = raf((timestamp) => { + timestamp; // $ExpectType number +}); + +handle; // $ExpectType number + +raf.cancel(handle); +raf.polyfill(); +raf.polyfill({}); diff --git a/types/raf/tsconfig.json b/types/raf/tsconfig.json new file mode 100644 index 0000000000..16b1eada34 --- /dev/null +++ b/types/raf/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "raf-tests.ts" + ] +} diff --git a/types/raf/tslint.json b/types/raf/tslint.json new file mode 100644 index 0000000000..a0051c9352 --- /dev/null +++ b/types/raf/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ae1b82aa9e12ac047ffce1c4672b2c33ac9ecc9e Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 1 Jan 2019 23:39:02 -0500 Subject: [PATCH 097/225] fix tests --- types/raf/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/raf/index.d.ts b/types/raf/index.d.ts index ef7d214811..1cab1a2fc8 100644 --- a/types/raf/index.d.ts +++ b/types/raf/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for raf 3.4.0 +// Type definitions for raf 3.4 // Project: https://github.com/chrisdickinson/raf#readme // Definitions by: Ben Lorantfy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,6 @@ declare const raf: { (callback: (timestamp: number) => void): number; cancel: (handle: number) => void; polyfill: (globalObject?: any) => void; -} +}; export default raf; From df1b008f58a0826f6fc374fb7d326b11a531aac4 Mon Sep 17 00:00:00 2001 From: Nathanael Date: Wed, 2 Jan 2019 02:03:27 -0600 Subject: [PATCH 098/225] Added type definition for Wallop --- package.json | 2 +- types/wallop/index.d.ts | 112 +++++++++++++++++++++++++++++++++++ types/wallop/tsconfig.json | 24 ++++++++ types/wallop/tslint.json | 1 + types/wallop/wallop-tests.ts | 14 +++++ 5 files changed, 152 insertions(+), 1 deletion(-) create mode 100644 types/wallop/index.d.ts create mode 100644 types/wallop/tsconfig.json create mode 100644 types/wallop/tslint.json create mode 100644 types/wallop/wallop-tests.ts diff --git a/package.json b/package.json index 7fc0358f27..4caeb0fe05 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "lint": "dtslint types" }, "devDependencies": { - "dtslint": "github:Microsoft/dtslint#production", + "dtslint": "^0.4.2", "types-publisher": "github:Microsoft/types-publisher#production" }, "dependencies": {} diff --git a/types/wallop/index.d.ts b/types/wallop/index.d.ts new file mode 100644 index 0000000000..fbc361d41c --- /dev/null +++ b/types/wallop/index.d.ts @@ -0,0 +1,112 @@ +// Type definitions for Wallop 2.4 +// Project: http://pedroduarte.me/wallop +// Definitions by: Nathanael McDaniel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = Wallop; +export as namespace Wallop; + +declare namespace Wallop { + interface Options { + /** + * Override class for "next" button. + * + * @default 'Wallop-buttonNext' + */ + buttonNextClass?: string; + + /** + * Override class for "previous" button. + * + * @default 'Wallop-buttonPrevious' + */ + buttonPreviousClass?: string; + + /** + * Enable/disable carousel mode. + * + * @default true + */ + carousel?: boolean; + + /** + * Override class for current item. + * + * @default 'Wallop-item--current' + */ + currentItemClass?: string; + + /** + * Override class that hides next item. + * + * @default 'Wallop-item--hideNext' + */ + hideNextClass?: string; + + /** + * Override class that hides previous item. + * + * @default 'Wallop-item--hidePrevious' + */ + hidePreviousClass?: string; + + /** + * Override class for item. + * + * @default 'Wallop-item' + */ + itemClass?: string; + + /** + * Override class for item that will show next. + * + * @default 'Wallop-item--showNext' + */ + showNextClass?: string; + + /** + * Override class for item that will showed previously. + * + * @default 'Wallop-item--showPrevious' + */ + showPreviousClass?: string; + } +} + +declare class Wallop { + /** + * Implement new instance of Wallop. + */ + constructor(selector: Element, options?: Wallop.Options); + + /** + * Advances to the slide with the given index. + */ + goTo(index: number): Wallop; + + /** + * Advances to next slide. + */ + next(): Wallop; + + /** + * Unbinds method from custom event. + */ + off(eventName: string, callback: () => void): Wallop; + + /** + * Bind method to custom event. + */ + on(eventName: string, callback: () => void): Wallop; + + /** + * Returns to previous slide. + */ + previous(): Wallop; + + /** + * Resets current Wallop instance to defaults. + */ + reset(): Wallop; +} diff --git a/types/wallop/tsconfig.json b/types/wallop/tsconfig.json new file mode 100644 index 0000000000..d2728e47ed --- /dev/null +++ b/types/wallop/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "wallop-tests.ts" + ] +} diff --git a/types/wallop/tslint.json b/types/wallop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wallop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wallop/wallop-tests.ts b/types/wallop/wallop-tests.ts new file mode 100644 index 0000000000..761d991df3 --- /dev/null +++ b/types/wallop/wallop-tests.ts @@ -0,0 +1,14 @@ +import Wallop = require('wallop'); + +const $element = document.createElement('div'); +$element.classList.add('.Wallop'); + +const slider = new Wallop($element); + +slider.goTo(0); // $ExpectType Wallop +slider.next(); // $ExpectType Wallop +slider.previous(); // $ExpectType Wallop +slider.reset(); // $ExpectType Wallop + +slider.on('change', () => { }); // $ExpectType Wallop +slider.off('change', () => { }); // $ExpectType Wallop From aee4551f5c1c4840727ed8cf3612271865d008bb Mon Sep 17 00:00:00 2001 From: Nathanael Date: Wed, 2 Jan 2019 02:07:34 -0600 Subject: [PATCH 099/225] Noticed accidental change of package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4caeb0fe05..7fc0358f27 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "lint": "dtslint types" }, "devDependencies": { - "dtslint": "^0.4.2", + "dtslint": "github:Microsoft/dtslint#production", "types-publisher": "github:Microsoft/types-publisher#production" }, "dependencies": {} From f1db5de7734187f8d4b9d603ad4faf2d1f6465dd Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Wed, 2 Jan 2019 10:18:28 +0100 Subject: [PATCH 100/225] Add Slugger to marked types --- types/marked/index.d.ts | 8 ++++++-- types/marked/marked-tests.ts | 5 +++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index 7eddfb4919..963a6f6697 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Marked 0.5 +// Type definitions for Marked 0.6 // Project: https://github.com/markedjs/marked // Definitions by: William Orr // BendingBender @@ -81,7 +81,7 @@ declare namespace marked { code(code: string, language: string, isEscaped: boolean): string; blockquote(quote: string): string; html(html: string): string; - heading(text: string, level: number, raw: string): string; + heading(text: string, level: number, raw: string, slugger: Slugger): string; hr(): string; list(body: string, ordered: boolean, start: number): string; listitem(text: string): string; @@ -109,6 +109,10 @@ declare namespace marked { lex(src: string): TokensList; } + class Slugger { + slug(value: string): string; + } + interface Rules { [ruleName: string]: RegExp | Rules; } diff --git a/types/marked/marked-tests.ts b/types/marked/marked-tests.ts index e1cb63042c..0edc376e43 100644 --- a/types/marked/marked-tests.ts +++ b/types/marked/marked-tests.ts @@ -44,6 +44,7 @@ console.log(tokens2); const re: RegExp | marked.Rules = lexer.rules['code']; const renderer = new marked.Renderer(); -renderer.heading = (text, level, raw) => { - return text + level.toString() + raw; +const slugger = new marked.Slugger(); +renderer.heading = (text, level, raw, slugger) => { + return text + level.toString() + slugger.slug(raw); }; From 1aa32163930520b27f50ae0e2c6528852d29d04f Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:30:07 +0200 Subject: [PATCH 101/225] Rewrite examples in JSX. --- types/linkifyjs/linkifyjs-tests.tsx | 58 +++++++++++++---------------- 1 file changed, 26 insertions(+), 32 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 2ec3979134..467bd39f84 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -153,44 +153,38 @@ describe("linkifyjs/react", () => { /* Usage */ - const options: LinkifyOptions = {}; - const content = "For help with GitHub.com, please email support@github.com"; - let rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - tagName: "p", - options - }, - React.createElement("span", content) - ), - rootElement - ); + { + // render() + let options = { + /* … */ + }; + let content = + "For help with GitHub.com, please email support@github.com"; + return ( + + {content} + + ); + } /* Events */ - const linkProps = { - onClick: (event: any) => { - if (!confirm("Are you sure you want to leave this page?")) { - event.preventDefault(); + { + let content = + "For help with GitHub.com, please email support@github.com"; + let linkProps = { + onClick: (event: any) => { + if (!confirm("Are you sure you want to leave this page?")) { + event.preventDefault(); + } } - } - }; + }; + return {content}; + } - rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - options: { attributes: linkProps } - }, - React.createElement("span", null) - ), - rootElement - ); + /* A few more test cases */ - rootElement = document.createElement("div"); + let rootElement = document.createElement("div"); ReactDOM.render( React.createElement( Linkify, From ef10efccb376d5b862fc9b337ea8455d71c7d4e5 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:32:58 +0200 Subject: [PATCH 102/225] Add JSX support. --- types/linkifyjs/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json index 7a19e25d0d..16becbcf0a 100644 --- a/types/linkifyjs/tsconfig.json +++ b/types/linkifyjs/tsconfig.json @@ -10,7 +10,8 @@ "typeRoots": ["../"], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" }, "files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.tsx"] } From ee0f28a96629669e46ae627859d808b8adb0b69e Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:34:05 +0200 Subject: [PATCH 103/225] Fix linting issues. --- types/linkifyjs/linkifyjs-tests.tsx | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 467bd39f84..fb4b99a72a 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -155,31 +155,29 @@ describe("linkifyjs/react", () => { { // render() - let options = { + const options = { /* … */ }; - let content = + const content = "For help with GitHub.com, please email support@github.com"; - return ( - - {content} - - ); + + {content} + ; } /* Events */ { - let content = + const content = "For help with GitHub.com, please email support@github.com"; - let linkProps = { + const linkProps = { onClick: (event: any) => { if (!confirm("Are you sure you want to leave this page?")) { event.preventDefault(); } } }; - return {content}; + {content}; } /* A few more test cases */ From f2777515136f394de5fb96ff092ae10db0536e4b Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:39:00 +0200 Subject: [PATCH 104/225] Use JSX in all tests. --- types/linkifyjs/linkifyjs-tests.tsx | 57 ++++++++++++----------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index fb4b99a72a..6b28d20528 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -182,39 +182,30 @@ describe("linkifyjs/react", () => { /* A few more test cases */ - let rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - {}, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); + /* Default values for all props */ + { + + Hello https://google.com + + } + + /* Custom class name */ - rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - options: { - className: "custom-class-name" - } - }, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); + { + + Hello https://google.com + + } - rootElement = document.createElement("div"); - ReactDOM.render( - React.createElement( - Linkify, - { - tagName: "p" - }, - React.createElement("span", "Hello https://google.com") - ), - rootElement - ); + /* Custom tag name */ + + { + + Hello https://google.com + + } }); From 627f354d1d7dbf8fc615bace43ba24bb25747cb7 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:39:46 +0200 Subject: [PATCH 105/225] Remove unused imports. --- types/linkifyjs/linkifyjs-tests.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 6b28d20528..57c91dae5a 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -1,6 +1,4 @@ import * as React from "react"; -import * as ReactDOM from "react-dom"; -import { LinkifyOptions } from "linkifyjs"; import linkifyHtml from "linkifyjs/html"; import Linkify from "linkifyjs/react"; From 5a2b7b2f0122df689f477f009d6450c0ad6b4944 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Wed, 2 Jan 2019 11:43:11 +0200 Subject: [PATCH 106/225] Work around prettier issue. --- types/linkifyjs/linkifyjs-tests.tsx | 36 ++++++++++++++++++----------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 57c91dae5a..23ae8e3722 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -182,28 +182,38 @@ describe("linkifyjs/react", () => { /* Default values for all props */ { + const content = + "For help with GitHub.com, please email support@github.com"; - Hello https://google.com - + {content} + ; } - + /* Custom class name */ { - - Hello https://google.com - + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; } /* Custom tag name */ { - - Hello https://google.com - + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; } }); From 3cd60ea66fa5dd50ccdd7120342898285eebcc2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Wed, 2 Jan 2019 12:44:21 +0200 Subject: [PATCH 107/225] fix(SCServer): any wsEngine to handle modules --- types/socketcluster-server/scserver.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts index dd598f981a..751a646bbd 100644 --- a/types/socketcluster-server/scserver.d.ts +++ b/types/socketcluster-server/scserver.d.ts @@ -83,7 +83,7 @@ declare namespace SCServer { // This can be the name of an npm module or a path to a Node.js module // to use as the WebSocket server engine. // You can now set this to 'sc-uws' for a massive speedup of at least 2x! - wsEngine?: string; + wsEngine?: any; // An ID to associate with this specific instance of SC // this may be useful if you are running an SC app on multiple From 46251ff1179014cd38c842e6e031286e2c5bb138 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Wed, 2 Jan 2019 12:44:35 +0200 Subject: [PATCH 108/225] fix(SCServer): add missing events --- types/socketcluster-server/scserver.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts index 751a646bbd..cef90acfed 100644 --- a/types/socketcluster-server/scserver.d.ts +++ b/types/socketcluster-server/scserver.d.ts @@ -33,6 +33,13 @@ declare class SCServer extends EventEmitter { constructor(options?: SCServer.SCServerOptions); on(event: "connection", listener: SCServer.connectionListenerFunction): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "disconnection" | "connectionAbort" | "closure", listener: SCServer.disconnectionListenerFunction): this; + on(event: "subscription", listener: SCServer.subscriptionListenerFunction): this; + on(event: "unsubscription", listener: SCServer.unsubscriptionListenerFunction): this; + on(event: "handshake", listener: SCServer.handshakeListenerFunction): this; + on(event: "badSocketAuthToken", listener: SCServer.badSocketAuthTokenListenerFunction): this; addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void; addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void; @@ -305,10 +312,20 @@ declare namespace SCServer { data?: any; } + interface badAuthStatus { + authError: Error; + signedAuthToken: string; + } + type nextMiddlewareFunction = (error?: true | string | Error) => void; type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void; type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void; type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; + type disconnectionListenerFunction = (scSocket: SCServerSocket, code: number, data: any) => void; + type subscriptionListenerFunction = (scSocket: SCServerSocket, name: string, options: {channel: string}) => void; + type unsubscriptionListenerFunction = (scSocket: SCServerSocket, name: string, channel: string) => void; + type handshakeListenerFunction = (scSocket: SCServerSocket) => void; + type badSocketAuthTokenListenerFunction = (scSocket: SCServerSocket, status: badAuthStatus) => void; interface SCCodecEngine { decode: (input: any) => any; From b94e246170fbd182788f258a590beb445320bc91 Mon Sep 17 00:00:00 2001 From: Henri Lahtinen Date: Wed, 2 Jan 2019 13:08:42 +0200 Subject: [PATCH 109/225] [react-native] Action types for Android date and time pickers --- types/react-native/index.d.ts | 42 ++++++++++++++++++++++--------- types/react-native/test/index.tsx | 19 +++++++++++++- 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 865a46eefa..eecd4cd148 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7226,13 +7226,19 @@ export interface DatePickerAndroidOpenOptions { } // Deduced from DatePickerAndroid.android.js -export interface DatePickerAndroidOpenReturn { - action: string; // "dateSetAction" | "dismissedAction" - year?: number; - month?: number; - day?: number; +export interface DatePickerAndroidDateSetAction { + action: 'dateSetAction'; + year: number; + month: number; + day: number; } +export interface DatePickerAndroidDismissedAction { + action: 'dismissedAction'; +} + +export type DatePickerAndroidOpenReturn = DatePickerAndroidDateSetAction | DatePickerAndroidDismissedAction + export interface DatePickerAndroidStatic { /** * Opens the standard Android date picker dialog. @@ -7257,12 +7263,12 @@ export interface DatePickerAndroidStatic { /** * A date has been selected. */ - dateSetAction: string; + dateSetAction: 'dateSetAction'; /** * The dialog has been dismissed. */ - dismissedAction: string; + dismissedAction: 'dismissedAction'; } export interface IntentAndroidStatic { @@ -8002,12 +8008,24 @@ export class StatusBar extends React.Component { */ export interface StatusBarIOSStatic extends NativeEventEmitter {} -type TimePickerAndroidOpenOptions = { +export interface TimePickerAndroidOpenOptions { hour?: number; minute?: number; is24Hour?: boolean; mode?: "clock" | "spinner" | "default"; -}; +} + +export interface TimePickerAndroidTimeSetAction { + action: 'timeSetAction'; + hour: number; + minute: number; +} + +export interface TimePickerAndroidDismissedAction { + action: 'dismissedAction'; +} + +export type TimePickerAndroidOpenReturn = TimePickerAndroidTimeSetAction | TimePickerAndroidDismissedAction; /** * Opens the standard Android time picker dialog. @@ -8049,17 +8067,17 @@ export interface TimePickerAndroidStatic { * still be resolved with action being `TimePickerAndroid.dismissedAction` and all the other keys * being undefined. **Always** check whether the `action` before reading the values. */ - open(options: TimePickerAndroidOpenOptions): Promise<{ action: string; hour: number; minute: number }>; + open(options: TimePickerAndroidOpenOptions): Promise; /** * A time has been selected. */ - timeSetAction: string; + timeSetAction: 'timeSetAction'; /** * The dialog has been dismissed. */ - dismissedAction: string; + dismissedAction: 'dismissedAction'; } /** diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 842882cc29..4186b082fb 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -78,6 +78,7 @@ import { KeyboardAvoidingView, Modal, TimePickerAndroid, + DatePickerAndroid, ViewPropTypes, requireNativeComponent, } from "react-native"; @@ -762,13 +763,29 @@ const AlertIOSTest = () => { const ModalTest = () => ; -const TimePickerAndroidTest = () => +const TimePickerAndroidTest = () => { TimePickerAndroid.open({ hour: 8, minute: 15, is24Hour: true, mode: "spinner", + }).then(result => { + if (result.action === TimePickerAndroid.timeSetAction) { + console.log('Time', result.hour, result.minute) + } }); +} + +const DatePickerAndroidTest = () => { + DatePickerAndroid.open({ + date: new Date(), + mode: 'calendar' + }).then(result => { + if (result.action === DatePickerAndroid.dateSetAction) { + console.log('Date', result.year, result.month, result.day) + } + }); +} class BridgedComponentTest extends React.Component { static propTypes = { From cf569891f458d6bd00848d2f1ee929c02adecb53 Mon Sep 17 00:00:00 2001 From: Sameer KC Date: Wed, 2 Jan 2019 12:46:40 +0100 Subject: [PATCH 110/225] Type definitions for node-gettext --- node-gettext/index.d.ts | 26 +++++++++++++++++++++++++ node-gettext/node-gettext-tests.ts | 31 ++++++++++++++++++++++++++++++ node-gettext/tsconfig.json | 22 +++++++++++++++++++++ node-gettext/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 node-gettext/index.d.ts create mode 100644 node-gettext/node-gettext-tests.ts create mode 100644 node-gettext/tsconfig.json create mode 100644 node-gettext/tslint.json diff --git a/node-gettext/index.d.ts b/node-gettext/index.d.ts new file mode 100644 index 0000000000..4d0f760e99 --- /dev/null +++ b/node-gettext/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for node-gettext 2.0 +// Project: http://github.com/alexanderwallin/node-gettext +// Definitions by: Sameer K.C. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default class GetText { + constructor(options?: { debug: boolean; }); + addTranslations(locale: string, domain: string, translations: object): void; + dgettext(domain: string, msgid: string): string; + dngettext(domain: string, msgid: string, msgidPlural: string, count: number): string; + dnpgettext(domain: string, msgctxt: string, msgid: string, msgidPlural: string, count: number): string; + dpgettext(domain: string, msgctxt: string, msgid: string): string; + emit(eventName: string, eventData: any): void; + getComment(domain: string, msgctxt: string, msgid: string): object | boolean; + gettext(msgid: string): string; + ngettext(msgid: string, msgidPlural: string, count: number): string; + npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string; + off(eventName: string, callback: (params: any) => void): string; + on(eventName: string, callback: (params: any) => void): void; + pgettext(msgctxt: string, msgid: string): string; + setLocale(locale: string): void; + setTextDomain(domain: string): void; + static getLanguageCode(locale: string): string; + textdomain(domain: string): void; + warn(message: string): void; +} diff --git a/node-gettext/node-gettext-tests.ts b/node-gettext/node-gettext-tests.ts new file mode 100644 index 0000000000..df01ae82c9 --- /dev/null +++ b/node-gettext/node-gettext-tests.ts @@ -0,0 +1,31 @@ +import Gettext from 'node-gettext'; + +const translations = {}; +const gt = new Gettext({ debug: true }); +const msgid = 'Get translation'; +const msgidPlural = 'Get translations'; +const domain = 'domain'; +const msgctxt = 'context'; +const count = 2; + +gt.addTranslations('en-US', 'messages', translations); +gt.setTextDomain(domain); +gt.textdomain(domain); +gt.setLocale('en-US'); +gt.gettext(msgid); +gt.dgettext('', msgid); +gt.dngettext(domain, msgid, msgidPlural, count); +gt.dnpgettext(domain, msgctxt, msgid, msgidPlural, count); +gt.dpgettext(domain, msgctxt, msgid); +gt.getComment(domain, msgctxt, msgid); +gt.ngettext(msgid, msgidPlural, count); +gt.npgettext(msgctxt, msgid, msgidPlural, count); +gt.pgettext(msgctxt, msgid); +Gettext.getLanguageCode('en-US'); +gt.warn('warning'); +const errorListener = (error: string) => { + // do something; +}; +gt.on('error', errorListener); +gt.emit('error', 'Error occurred'); +gt.off('error', errorListener); diff --git a/node-gettext/tsconfig.json b/node-gettext/tsconfig.json new file mode 100644 index 0000000000..fa6bede617 --- /dev/null +++ b/node-gettext/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-gettext-tests.ts" + ] +} diff --git a/node-gettext/tslint.json b/node-gettext/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/node-gettext/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0f03ece7f9c32fed0e7da243c817ba17af6878eb Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Wed, 2 Jan 2019 12:47:42 +0100 Subject: [PATCH 111/225] Fix return type of getForeignObjectsAsync --- types/iobroker/index.d.ts | 6 +++--- types/iobroker/iobroker-tests.ts | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 314d8c8e30..4cfbddc2a2 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1125,9 +1125,9 @@ declare global { getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void; // tslint:enable:unified-signatures /** Get foreign objects by pattern, by specific type and resolve their enums. */ - getForeignObjectsAsync(pattern: string, options?: unknown): Promise>; - getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise>; - getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise>; /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index fcdc4d5c9e..c7e0f1ec22 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -170,6 +170,9 @@ adapter.getForeignObject("obj.id", (err, obj) => { }); adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); +adapter.getForeignObjects("*", (err, objs) => { objs["foo"]._id.toLowerCase(); }) +adapter.getForeignObjectsAsync("*").then(objs => objs["foo"]._id.toLowerCase()); + adapter.subscribeObjects("*"); adapter.subscribeStates("*"); adapter.subscribeForeignObjects("*"); From 2b6f0e732d5b63352369dc658b751aa56d8f4b1c Mon Sep 17 00:00:00 2001 From: Jan Dolezel Date: Wed, 2 Jan 2019 15:03:21 +0100 Subject: [PATCH 112/225] Fixes after #31704 --- types/koa-router/index.d.ts | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 8d8f35df6b..81b0f697e6 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -19,12 +19,6 @@ import * as Koa from "koa"; -declare module "koa" { - interface Context { - params: any; - } -} - declare namespace Router { export interface IRouterOptions { /** @@ -49,7 +43,7 @@ declare namespace Router { strict?: boolean; } - export interface IRouterContext extends Koa.Context { + export interface IRouterContext { /** * url params */ @@ -61,11 +55,11 @@ declare namespace Router { } export interface IMiddleware { - (ctx: Router.IRouterContext, next: () => Promise): any; + (ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; } export interface IParamMiddleware { - (param: string, ctx: Router.IRouterContext, next: () => Promise): any; + (param: string, ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -88,7 +82,7 @@ declare namespace Router { sensitive?: boolean; strict?: boolean; } - + export interface IUrlOptionsQuery { query: object | string; } @@ -190,19 +184,19 @@ declare class Router { */ put(name: string, path: string | RegExp, ...middleware: Array): Router; put(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP link method */ link(name: string, path: string | RegExp, ...middleware: Array): Router; link(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP unlink method */ unlink(name: string, path: string | RegExp, ...middleware: Array): Router; unlink(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP delete method @@ -283,21 +277,21 @@ declare class Router { /** * Generate URL for route. Takes either map of named `params` or series of * arguments (for regular expression routes) - * + * * router = new Router(); * router.get('user', "/users/:id", ... - * + * * router.url('user', { id: 3 }); * // => "/users/3" - * + * * Query can be generated from third argument: - * + * * router.url('user', { id: 3 }, { query: { limit: 1 } }); * // => "/users/3?limit=1" - * + * * router.url('user', { id: 3 }, { query: "limit=1" }); * // => "/users/3?limit=1" - * + * */ url(name: string, params: any, options?: Router.IUrlOptionsQuery): string; url(name: string, params: any, options?: Router.IUrlOptionsQuery): Error; From 820145214ba85fac91f8fdfd6d97b9ce617666a0 Mon Sep 17 00:00:00 2001 From: Jan Dolezel Date: Wed, 2 Jan 2019 15:06:56 +0100 Subject: [PATCH 113/225] Opting into typesafe koa --- types/koa-router/koa-router-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index e1c90c636d..51e95fb8a5 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -1,7 +1,7 @@ import Koa = require("koa"); import Router = require("koa-router"); -const app = new Koa(); +const app = new Koa<{}, {}>(); const router = new Router({ prefix: "/users" From fea3cc70b18562ca76354f300918159f6f41f656 Mon Sep 17 00:00:00 2001 From: Jonathan Price Date: Wed, 2 Jan 2019 14:17:41 +0000 Subject: [PATCH 114/225] [onesignal-cordova-plugin] [cordova-plugin-x-socialsharing] Make Cordova plugins compatible with each other --- types/cordova-plugin-x-socialsharing/index.d.ts | 6 +++--- types/onesignal-cordova-plugin/index.d.ts | 8 ++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/types/cordova-plugin-x-socialsharing/index.d.ts b/types/cordova-plugin-x-socialsharing/index.d.ts index a5105c898c..d1a4740b58 100644 --- a/types/cordova-plugin-x-socialsharing/index.d.ts +++ b/types/cordova-plugin-x-socialsharing/index.d.ts @@ -1,13 +1,13 @@ -// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8 +// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.9 // Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin // Definitions by: Markus Wagner , Larry Bahr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { - plugins: Plugins; + plugins: CordovaPlugins; } -interface Plugins { +interface CordovaPlugins { socialsharing: SocialSharingPlugin.SocialSharing; } diff --git a/types/onesignal-cordova-plugin/index.d.ts b/types/onesignal-cordova-plugin/index.d.ts index d2c2534829..28dd8b7159 100644 --- a/types/onesignal-cordova-plugin/index.d.ts +++ b/types/onesignal-cordova-plugin/index.d.ts @@ -1,10 +1,14 @@ -// Type definitions for onesignal-cordova-plugin 2.2 +// Type definitions for onesignal-cordova-plugin 2.2.1 // Project: https://github.com/onesignal/OneSignal-Cordova-SDK#readme // Definitions by: David Broder-Rodgers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { - plugins: { OneSignal: OneSignalCordovaPlugin.OneSignalCordovaPlugin }; + plugins: CordovaPlugins; +} + +interface CordovaPlugins { + OneSignal: OneSignalCordovaPlugin.OneSignalCordovaPlugin; } declare namespace OneSignalCordovaPlugin { From 8508ed3ddc883f4b3b39cf35bfac4e66bacb153e Mon Sep 17 00:00:00 2001 From: Jonathan Price Date: Wed, 2 Jan 2019 14:43:59 +0000 Subject: [PATCH 115/225] Remove patch version from header --- types/onesignal-cordova-plugin/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/onesignal-cordova-plugin/index.d.ts b/types/onesignal-cordova-plugin/index.d.ts index 28dd8b7159..09b6b63d90 100644 --- a/types/onesignal-cordova-plugin/index.d.ts +++ b/types/onesignal-cordova-plugin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for onesignal-cordova-plugin 2.2.1 +// Type definitions for onesignal-cordova-plugin 2.2 // Project: https://github.com/onesignal/OneSignal-Cordova-SDK#readme // Definitions by: David Broder-Rodgers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From f17c61f5c6e5813399d11e68d4fa0df2063e8890 Mon Sep 17 00:00:00 2001 From: Sameer KC Date: Wed, 2 Jan 2019 15:56:33 +0100 Subject: [PATCH 116/225] CommonJS style import No default in npm module --- node-gettext/conf/tslint.json | 1 + node-gettext/index.d.ts | 3 ++- node-gettext/node-gettext-tests.ts | 3 +++ node-gettext/tsconfig.json | 4 +++- 4 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 node-gettext/conf/tslint.json diff --git a/node-gettext/conf/tslint.json b/node-gettext/conf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/node-gettext/conf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/node-gettext/index.d.ts b/node-gettext/index.d.ts index 4d0f760e99..735f8db84b 100644 --- a/node-gettext/index.d.ts +++ b/node-gettext/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Sameer K.C. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export default class GetText { +export = GetText; +declare class GetText { constructor(options?: { debug: boolean; }); addTranslations(locale: string, domain: string, translations: object): void; dgettext(domain: string, msgid: string): string; diff --git a/node-gettext/node-gettext-tests.ts b/node-gettext/node-gettext-tests.ts index df01ae82c9..e20e6aacac 100644 --- a/node-gettext/node-gettext-tests.ts +++ b/node-gettext/node-gettext-tests.ts @@ -1,4 +1,7 @@ +// with tsc v 2.7 & esModuleInterop & allowSyntheticDefaultImports enabled in tsconfig.json import Gettext from 'node-gettext'; +// or without +// import Gettext = require('node-getttext'); const translations = {}; const gt = new Gettext({ debug: true }); diff --git a/node-gettext/tsconfig.json b/node-gettext/tsconfig.json index fa6bede617..9306d23426 100644 --- a/node-gettext/tsconfig.json +++ b/node-gettext/tsconfig.json @@ -13,7 +13,9 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true }, "files": [ "index.d.ts", From 141cb7e6b3c073624e6ab8654f5fa76db45a2a7b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Wed, 2 Jan 2019 16:51:32 +0100 Subject: [PATCH 117/225] Fix missing semicolon --- types/iobroker/iobroker-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index c7e0f1ec22..2ee7da83d5 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -170,7 +170,7 @@ adapter.getForeignObject("obj.id", (err, obj) => { }); adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); -adapter.getForeignObjects("*", (err, objs) => { objs["foo"]._id.toLowerCase(); }) +adapter.getForeignObjects("*", (err, objs) => objs["foo"]._id.toLowerCase()); adapter.getForeignObjectsAsync("*").then(objs => objs["foo"]._id.toLowerCase()); adapter.subscribeObjects("*"); From 283edb4db7fa99ea33db2f7dc740865aa9dc9b25 Mon Sep 17 00:00:00 2001 From: Nathanael McDaniel Date: Wed, 2 Jan 2019 10:35:16 -0600 Subject: [PATCH 118/225] Update index.d.ts Updated project URL with GitHub repo. --- types/wallop/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/wallop/index.d.ts b/types/wallop/index.d.ts index fbc361d41c..a86bd4e99e 100644 --- a/types/wallop/index.d.ts +++ b/types/wallop/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for Wallop 2.4 -// Project: http://pedroduarte.me/wallop +// Project: https://github.com/peduarte/wallop // Definitions by: Nathanael McDaniel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From 82a243caea68d65ea3331f852534363cff90ac4f Mon Sep 17 00:00:00 2001 From: Retsam Date: Thu, 20 Dec 2018 16:20:20 -0500 Subject: [PATCH 119/225] Fix issue with computeds and KnockoutObservable The fix for #26700 caused this issue, where a KnockoutComputed inferred as KnockoutObservable when using conditional type inference --- types/knockout/index.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index fa0e195788..8bf99b79db 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -140,7 +140,7 @@ interface KnockoutSubscribableStatic { interface KnockoutSubscription { /** - * Terminates a subscription + * Terminates a subscription */ dispose(): void; } @@ -213,9 +213,6 @@ interface KnockoutReadonlyComputed extends KnockoutReadonlyObservable { interface KnockoutComputed extends KnockoutReadonlyComputed, KnockoutObservable, KnockoutComputedFunctions { fn: KnockoutComputedFunctions; - // It's possible for 'a' to be undefined, since the equalityComparer is run on the initial - // computation with undefined as the first argument. This is user-relevant for deferred computeds. - equalityComparer(a: T | undefined, b: T): boolean; /** * Manually disposes the computed observable, clearing all subscriptions to dependencies. * This function is useful if you want to stop a computed observable from being updated or want to clean up memory for a From 882d354de4242e1808c42329a3ed146ac1245669 Mon Sep 17 00:00:00 2001 From: jlmessenger Date: Wed, 2 Jan 2019 13:12:26 -0500 Subject: [PATCH 120/225] [@pollyjs/adapter-node-http] Add types for initial 1.4 release --- types/pollyjs__adapter-node-http/index.d.ts | 9 +++++ .../pollyjs__adapter-node-http-tests.ts | 8 ++++ .../pollyjs__adapter-node-http/tsconfig.json | 40 +++++++++++++++++++ types/pollyjs__adapter-node-http/tslint.json | 1 + 4 files changed, 58 insertions(+) create mode 100644 types/pollyjs__adapter-node-http/index.d.ts create mode 100644 types/pollyjs__adapter-node-http/pollyjs__adapter-node-http-tests.ts create mode 100644 types/pollyjs__adapter-node-http/tsconfig.json create mode 100644 types/pollyjs__adapter-node-http/tslint.json diff --git a/types/pollyjs__adapter-node-http/index.d.ts b/types/pollyjs__adapter-node-http/index.d.ts new file mode 100644 index 0000000000..1ffab20c7e --- /dev/null +++ b/types/pollyjs__adapter-node-http/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for @pollyjs/adapter-node-http 1.4 +// Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http +// Definitions by: jlmessenger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Adapter from '@pollyjs/adapter'; + +export default class HttpAdapter extends Adapter {} diff --git a/types/pollyjs__adapter-node-http/pollyjs__adapter-node-http-tests.ts b/types/pollyjs__adapter-node-http/pollyjs__adapter-node-http-tests.ts new file mode 100644 index 0000000000..2948cd30f7 --- /dev/null +++ b/types/pollyjs__adapter-node-http/pollyjs__adapter-node-http-tests.ts @@ -0,0 +1,8 @@ +import HttpAdapter from '@pollyjs/adapter-node-http'; +import { Polly } from '@pollyjs/core'; + +Polly.register(HttpAdapter); + +new Polly('', { + adapters: ['node-http', HttpAdapter] +}); diff --git a/types/pollyjs__adapter-node-http/tsconfig.json b/types/pollyjs__adapter-node-http/tsconfig.json new file mode 100644 index 0000000000..fe0d38d6c2 --- /dev/null +++ b/types/pollyjs__adapter-node-http/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/adapter": [ + "pollyjs__adapter" + ], + "@pollyjs/adapter-node-http": [ + "pollyjs__adapter-node-http" + ], + "@pollyjs/persister": [ + "pollyjs__persister" + ], + "@pollyjs/utils": [ + "pollyjs__utils" + ] + } + }, + "files": [ + "index.d.ts", + "pollyjs__adapter-node-http-tests.ts" + ] +} diff --git a/types/pollyjs__adapter-node-http/tslint.json b/types/pollyjs__adapter-node-http/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__adapter-node-http/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 498f3072fba17758f752481b640f9cd083e998bc Mon Sep 17 00:00:00 2001 From: Mike North Date: Wed, 2 Jan 2019 12:34:16 -0800 Subject: [PATCH 121/225] chore: fix package name in dtslint header --- types/treeify/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/treeify/index.d.ts b/types/treeify/index.d.ts index 29375cf7ba..938772cc99 100644 --- a/types/treeify/index.d.ts +++ b/types/treeify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for tress 1.0 +// Type definitions for treeify 1.0 // Project: https://github.com/notatestuser/treeify // Definitions by: Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 099d1b993b6ec62661a8b370d3c6c16350c629ef Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 2 Jan 2019 13:10:49 -0800 Subject: [PATCH 122/225] Adding overloads for callback methods to allow for no options but a callback --- types/office-js-preview/index.d.ts | 61 +++++++++++++++++++++++++++ types/office-js/index.d.ts | 66 ++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 2803e305ff..911a488a73 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -1103,6 +1103,7 @@ declare namespace Office { * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. */ displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + displayDialogAsync(startAddress: string, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. * @param message Accepts a message from the dialog to deliver to the add-in. In addition to a boolean, anything that can serialized to a string including JSON and XML can be sent. @@ -2295,6 +2296,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => void): void; /** * Returns the data contained within the binding. * @@ -2310,6 +2312,7 @@ declare namespace Office { * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. */ getDataAsync(options?: GetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + getDataAsync(callback?: (result: AsyncResult) => void): void; /** * Removes the specified handler from the binding for the specified event type. * @@ -2321,6 +2324,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes data to the bound section of the document represented by the specified binding object. * @@ -2452,6 +2456,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + setDataAsync(data: TableData | any, callback?: (result: AsyncResult) => void): void; } /** @@ -2601,6 +2606,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the specified named item. */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, options?: AddBindingFromNamedItemOptions, callback?: (result: AsyncResult) => void): void; + addFromNamedItemAsync(itemName: string, bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding by prompting the user to make a selection on the document. * @@ -2632,6 +2638,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromPromptAsync(bindingType: BindingType, options?: AddBindingFromPromptOptions, callback?: (result: AsyncResult) => void): void; + addFromPromptAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding based on the user's current selection. * @@ -2668,6 +2675,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromSelectionAsync(bindingType: BindingType, options?: AddBindingFromSelectionOptions, callback?: (result: AsyncResult) => void): void; + addFromSelectionAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Gets all bindings that were previously created. * @@ -2695,6 +2703,7 @@ declare namespace Office { * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. */ getAllAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAllAsync(callback?: (result: AsyncResult) => void): void; /** * Retrieves a binding based on its Name * @@ -2725,6 +2734,7 @@ declare namespace Office { * The `value` property of the result is the Binding object specified by the id in the call. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Removes the binding from the document * @@ -2754,6 +2764,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ releaseByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + releaseByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; } /** * Represents an XML node in a tree in a document. @@ -2809,6 +2820,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Gets the node value. * @@ -2820,6 +2832,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the value of the referenced node. */ getNodeValueAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodeValueAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the text of an XML node in a custom XML part. * @@ -2831,6 +2844,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the inner text of the referenced nodes. */ getTextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTextAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the node's XML. * @@ -2842,6 +2856,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced node. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Sets the node value. * @@ -2853,6 +2868,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setNodeValueAsync(value: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setNodeValueAsync(value: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously sets the text of an XML node in a custom XML part. * @@ -2866,6 +2882,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setTextAsync(text: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTextAsync(text: string, callback?: (result: AsyncResult) => void): void; /** * Sets the node XML. * @@ -2877,6 +2894,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setXmlAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setXmlAsync(xml: string, callback?: (result: AsyncResult) => void): void; } /** * Represents a single CustomXMLPart in an {@link Office.CustomXmlParts} collection. @@ -2927,6 +2945,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, callback?: (result: AsyncResult) => void): void; /** * Deletes the Custom XML Part. * @@ -2936,6 +2955,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + deleteAsync(callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. * @@ -2947,6 +2967,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the XML inside this custom XML part. * @@ -2957,6 +2978,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @@ -2969,6 +2991,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, callback?: (result: AsyncResult) => void): void; } /** @@ -3108,6 +3131,7 @@ declare namespace Office { * The `value` property of the result is the newly created CustomXmlPart object. */ addAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addAsync(xml: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part by its id. * @@ -3118,6 +3142,7 @@ declare namespace Office { * If there is no custom XML part with the specified id, the method returns null. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part(s) by its namespace. * @@ -3127,6 +3152,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. */ getByNamespaceAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByNamespaceAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** * Represents a collection of CustomXmlPart objects. @@ -3162,6 +3188,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addNamespaceAsync(prefix: string, ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addNamespaceAsync(prefix: string, ns: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the namespace mapped to the specified prefix. * @@ -3176,6 +3203,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. */ getNamespaceAsync(prefix: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNamespaceAsync(prefix: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the prefix for the specified namespace. * @@ -3190,6 +3218,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the prefix of the specified namespace. */ getPrefixAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getPrefixAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** * An abstract class that represents the document the add-in is interacting with. @@ -3345,6 +3374,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Returns the state of the current view of the presentation (edit or read). * @@ -3374,6 +3404,7 @@ declare namespace Office { * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. */ getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void; + getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void; /** * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). * Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure. @@ -3418,6 +3449,7 @@ declare namespace Office { * The `value` property of the result is the File object. */ getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult) => void): void; + getFileAsync(fileType: FileType, callback?: (result: AsyncResult) => void): void; /** * Gets file properties of the current document. * @@ -3447,6 +3479,7 @@ declare namespace Office { * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). */ getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getFilePropertiesAsync(callback?: (result: AsyncResult) => void): void; /** * Reads the data contained in the current selection in the document. * @@ -3539,6 +3572,7 @@ declare namespace Office { * (See Remarks for more information about data coercion.) */ getSelectedDataAsync(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. * @@ -3581,6 +3615,7 @@ declare namespace Office { * The `value` property of the result is the current view. */ goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult) => void): void; + goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @@ -3610,6 +3645,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes the specified data into the current selection. * @@ -3723,6 +3759,7 @@ declare namespace Office { * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. */ setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get Project field (Ex. ProjectWebAccessURL). * @param fieldId Project level fields. @@ -3747,6 +3784,7 @@ declare namespace Office { * */ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) * @param resourceId Either a string or value of the Resource Id. @@ -3772,6 +3810,7 @@ declare namespace Office { * */ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Resource's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3795,6 +3834,7 @@ declare namespace Office { * */ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedResourceAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Task's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3818,6 +3858,7 @@ declare namespace Office { * */ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedTaskAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3843,6 +3884,7 @@ declare namespace Office { * */ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedViewAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. * @param taskId Either a string or value of the Task Id. @@ -3870,6 +3912,7 @@ declare namespace Office { * */ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskAsync(taskId: string, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get task field for provided task Id. (Ex. StartDate). * @param taskId Either a string or value of the Task Id. @@ -3895,6 +3938,7 @@ declare namespace Office { * */ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3920,6 +3964,7 @@ declare namespace Office { * */ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getWSSUrlAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of resources in the current project. * @@ -3946,6 +3991,7 @@ declare namespace Office { * */ getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getMaxResourceIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * @@ -3972,6 +4018,7 @@ declare namespace Office { * */ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getMaxTaskIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * @@ -3999,6 +4046,7 @@ declare namespace Office { * */ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * @@ -4026,6 +4074,7 @@ declare namespace Office { * */ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set resource field for specified resource Id. * @@ -4054,6 +4103,7 @@ declare namespace Office { * */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set task field for specified task Id. * @@ -4082,6 +4132,7 @@ declare namespace Office { * */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; } /** * Provides information about the document that raised the SelectionChanged event. @@ -4332,6 +4383,7 @@ declare namespace Office { * */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Retrieves the specified setting. * @@ -4487,6 +4539,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Persists the in-memory copy of the settings property bag in the document. * @@ -4544,6 +4597,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ saveAsync(options?: SaveSettingsOptions, callback?: (result: AsyncResult) => void): void; + saveAsync(callback?: (result: AsyncResult) => void): void; /** * Sets or creates the specified setting. * @@ -4804,6 +4858,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addColumnsAsync(tableData: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addColumnsAsync(tableData: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Adds the specified data to the table as additional rows. * @@ -4844,6 +4899,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addRowsAsync(rows: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addRowsAsync(rows: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. * @@ -4871,6 +4927,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAllDataValuesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + deleteAllDataValuesAsync(callback?: (result: AsyncResult) => void): void; /** * Clears formatting on the bound table. * @@ -4895,6 +4952,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ clearFormatsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + clearFormatsAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the formatting on specified items in the table. * @@ -4949,6 +5007,7 @@ declare namespace Office { * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. */ getFormatsAsync(cellReference?: any, formats?: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; + getFormatsAsync(cellReference?: any, formats?: any[], callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; /** * Sets formatting on specified items and data in the table. * @@ -5062,6 +5121,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setFormatsAsync(cellFormat: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setFormatsAsync(cellFormat: any[], callback?: (result: AsyncResult) => void): void; /** * Updates table formatting options on the bound table. * @@ -5115,6 +5175,7 @@ declare namespace Office { * */ setTableOptionsAsync(tableOptions: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** * Represents the data in a table or a {@link Office.TableBinding}. diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 4c451e9de6..d07693f783 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1103,6 +1103,7 @@ declare namespace Office { * @param callback - Optional. Accepts a callback method to handle the dialog creation attempt. If successful, the AsyncResult.value is a Dialog object. */ displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; + displayDialogAsync(startAddress: string, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. * @param message Accepts a message from the dialog to deliver to the add-in. In addition to a boolean, anything that can serialized to a string including JSON and XML can be sent. @@ -2295,6 +2296,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => void): void; /** * Returns the data contained within the binding. * @@ -2310,6 +2312,7 @@ declare namespace Office { * If the `coercionType` parameter is specified (and the call is successful), the data is returned in the format described in the CoercionType enumeration topic. */ getDataAsync(options?: GetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + getDataAsync(callback?: (result: AsyncResult) => void): void; /** * Removes the specified handler from the binding for the specified event type. * @@ -2321,6 +2324,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes data to the bound section of the document represented by the specified binding object. * @@ -2452,6 +2456,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setDataAsync(data: TableData | any, options?: SetBindingDataOptions, callback?: (result: AsyncResult) => void): void; + setDataAsync(data: TableData | any, callback?: (result: AsyncResult) => void): void; } /** @@ -2601,6 +2606,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the specified named item. */ addFromNamedItemAsync(itemName: string, bindingType: BindingType, options?: AddBindingFromNamedItemOptions, callback?: (result: AsyncResult) => void): void; + addFromNamedItemAsync(itemName: string, bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding by prompting the user to make a selection on the document. * @@ -2632,6 +2638,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromPromptAsync(bindingType: BindingType, options?: AddBindingFromPromptOptions, callback?: (result: AsyncResult) => void): void; + addFromPromptAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Create a binding based on the user's current selection. * @@ -2668,6 +2675,7 @@ declare namespace Office { * The `value` property of the result is the Binding object that represents the selection specified by the user. */ addFromSelectionAsync(bindingType: BindingType, options?: AddBindingFromSelectionOptions, callback?: (result: AsyncResult) => void): void; + addFromSelectionAsync(bindingType: BindingType, callback?: (result: AsyncResult) => void): void; /** * Gets all bindings that were previously created. * @@ -2695,6 +2703,7 @@ declare namespace Office { * The `value` property of the result is an array that contains each binding created for the referenced Bindings object. */ getAllAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAllAsync(callback?: (result: AsyncResult) => void): void; /** * Retrieves a binding based on its Name * @@ -2725,6 +2734,7 @@ declare namespace Office { * The `value` property of the result is the Binding object specified by the id in the call. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Removes the binding from the document * @@ -2754,6 +2764,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ releaseByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + releaseByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; } /** * Represents an XML node in a tree in a document. @@ -2809,6 +2820,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the `xPath` parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Gets the node value. * @@ -2820,6 +2832,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the value of the referenced node. */ getNodeValueAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodeValueAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the text of an XML node in a custom XML part. * @@ -2831,6 +2844,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the inner text of the referenced nodes. */ getTextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTextAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the node's XML. * @@ -2842,6 +2856,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced node. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Sets the node value. * @@ -2853,6 +2868,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setNodeValueAsync(value: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setNodeValueAsync(value: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously sets the text of an XML node in a custom XML part. * @@ -2866,6 +2882,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setTextAsync(text: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTextAsync(text: string, callback?: (result: AsyncResult) => void): void; /** * Sets the node XML. * @@ -2877,6 +2894,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setXmlAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setXmlAsync(xml: string, callback?: (result: AsyncResult) => void): void; } /** * Represents a single CustomXMLPart in an {@link Office.CustomXmlParts} collection. @@ -2927,6 +2945,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: (result: any) => void, callback?: (result: AsyncResult) => void): void; /** * Deletes the Custom XML Part. * @@ -2936,6 +2955,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + deleteAsync(callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. * @@ -2947,6 +2967,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlNode objects that represent the nodes specified by the XPath expression passed to the xPath parameter. */ getNodesAsync(xPath: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNodesAsync(xPath: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the XML inside this custom XML part. * @@ -2957,6 +2978,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the XML of the referenced CustomXmlPart object. */ getXmlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getXmlAsync(callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @@ -2969,6 +2991,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, handler?: (result: any) => void, callback?: (result: AsyncResult) => void): void; } /** @@ -3108,6 +3131,7 @@ declare namespace Office { * The `value` property of the result is the newly created CustomXmlPart object. */ addAsync(xml: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addAsync(xml: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part by its id. * @@ -3118,6 +3142,7 @@ declare namespace Office { * If there is no custom XML part with the specified id, the method returns null. */ getByIdAsync(id: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByIdAsync(id: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the specified custom XML part(s) by its namespace. * @@ -3127,6 +3152,7 @@ declare namespace Office { * The `value` property of the result is an array of CustomXmlPart objects that match the specified namespace. */ getByNamespaceAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getByNamespaceAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** * Represents a collection of CustomXmlPart objects. @@ -3162,6 +3188,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addNamespaceAsync(prefix: string, ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addNamespaceAsync(prefix: string, ns: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the namespace mapped to the specified prefix. * @@ -3176,6 +3203,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the namespace mapped to the specified prefix. */ getNamespaceAsync(prefix: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getNamespaceAsync(prefix: string, callback?: (result: AsyncResult) => void): void; /** * Asynchronously gets the prefix for the specified namespace. * @@ -3190,6 +3218,7 @@ declare namespace Office { * The `value` property of the result is a string that contains the prefix of the specified namespace. */ getPrefixAsync(ns: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getPrefixAsync(ns: string, callback?: (result: AsyncResult) => void): void; } /** * An abstract class that represents the document the add-in is interacting with. @@ -3345,6 +3374,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Returns the state of the current view of the presentation (edit or read). * @@ -3374,6 +3404,7 @@ declare namespace Office { * such as Normal or Outline View. "read" corresponds to either Slide Show or Reading View. */ getActiveViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult<"edit" | "read">) => void): void; + getActiveViewAsync(callback?: (result: AsyncResult<"edit" | "read">) => void): void; /** * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). * Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure. @@ -3418,6 +3449,7 @@ declare namespace Office { * The `value` property of the result is the File object. */ getFileAsync(fileType: FileType, options?: GetFileOptions, callback?: (result: AsyncResult) => void): void; + getFileAsync(fileType: FileType, callback?: (result: AsyncResult) => void): void; /** * Gets file properties of the current document. * @@ -3447,6 +3479,7 @@ declare namespace Office { * The `value` property of the result is the file's properties (with the URL found at `asyncResult.value.url`). */ getFilePropertiesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getFilePropertiesAsync(callback?: (result: AsyncResult) => void): void; /** * Reads the data contained in the current selection in the document. * @@ -3539,6 +3572,7 @@ declare namespace Office { * (See Remarks for more information about data coercion.) */ getSelectedDataAsync(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. * @@ -3581,6 +3615,7 @@ declare namespace Office { * The `value` property of the result is the current view. */ goToByIdAsync(id: string | number, goToType: GoToType, options?: GoToByIdOptions, callback?: (result: AsyncResult) => void): void; + goToByIdAsync(id: string | number, goToType: GoToType, callback?: (result: AsyncResult) => void): void; /** * Removes an event handler for the specified event type. * @@ -3610,6 +3645,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Writes the specified data into the current selection. * @@ -3723,6 +3759,7 @@ declare namespace Office { * The AsyncResult.value property always returns undefined because there is no object or data to retrieve. */ setSelectedDataAsync(data: string | TableData | any[][], options?: SetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + setSelectedDataAsync(data: string | TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get Project field (Ex. ProjectWebAccessURL). * @param fieldId Project level fields. @@ -3747,6 +3784,7 @@ declare namespace Office { * */ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getProjectFieldAsync(fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get resource field for provided resource Id. (Ex.ResourceName) * @param resourceId Either a string or value of the Resource Id. @@ -3772,6 +3810,7 @@ declare namespace Office { * */ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getResourceFieldAsync(resourceId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Resource's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3795,6 +3834,7 @@ declare namespace Office { * */ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedResourceAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Task's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3818,6 +3858,7 @@ declare namespace Office { * */ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedTaskAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3843,6 +3884,7 @@ declare namespace Office { * */ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getSelectedViewAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the Task Name, WSS Task Id, and ResourceNames for given taskId. * @param taskId Either a string or value of the Task Id. @@ -3870,6 +3912,7 @@ declare namespace Office { * */ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskAsync(taskId: string, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get task field for provided task Id. (Ex. StartDate). * @param taskId Either a string or value of the Task Id. @@ -3895,6 +3938,7 @@ declare namespace Office { * */ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskFieldAsync(taskId: string, fieldId: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3920,6 +3964,7 @@ declare namespace Office { * */ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getWSSUrlAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of resources in the current project. * @@ -3946,6 +3991,7 @@ declare namespace Office { * */ getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getMaxResourceIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * @@ -3972,6 +4018,7 @@ declare namespace Office { * */ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getMaxTaskIndexAsync(callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * @@ -3999,6 +4046,7 @@ declare namespace Office { * */ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getResourceByIndexAsync(resourceIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * @@ -4026,6 +4074,7 @@ declare namespace Office { * */ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTaskByIndexAsync(taskIndex: number, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set resource field for specified resource Id. * @@ -4054,6 +4103,7 @@ declare namespace Office { * */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Set task field for specified task Id. * @@ -4082,6 +4132,7 @@ declare namespace Office { * */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, callback?: (result: AsyncResult) => void): void; } /** * Provides information about the document that raised the SelectionChanged event. @@ -4332,6 +4383,7 @@ declare namespace Office { * */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; /** * Retrieves the specified setting. * @@ -4487,6 +4539,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, callback?: (result: AsyncResult) => void): void; /** * Persists the in-memory copy of the settings property bag in the document. * @@ -4544,6 +4597,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ saveAsync(options?: SaveSettingsOptions, callback?: (result: AsyncResult) => void): void; + saveAsync(callback?: (result: AsyncResult) => void): void; /** * Sets or creates the specified setting. * @@ -4804,6 +4858,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addColumnsAsync(tableData: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addColumnsAsync(tableData: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Adds the specified data to the table as additional rows. * @@ -4844,6 +4899,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ addRowsAsync(rows: TableData | any[][], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addRowsAsync(rows: TableData | any[][], callback?: (result: AsyncResult) => void): void; /** * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. * @@ -4871,6 +4927,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ deleteAllDataValuesAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + deleteAllDataValuesAsync(callback?: (result: AsyncResult) => void): void; /** * Clears formatting on the bound table. * @@ -4895,6 +4952,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ clearFormatsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + clearFormatsAsync(callback?: (result: AsyncResult) => void): void; /** * Gets the formatting on specified items in the table. * @@ -4949,6 +5007,7 @@ declare namespace Office { * The `value` property of the result is an array containing one or more JavaScript objects specifying the formatting of their corresponding cells. */ getFormatsAsync(cellReference?: any, formats?: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; + getFormatsAsync(cellReference?: any, formats?: any[], callback?: (result: AsyncResult< ({ cells: any, format: any})[]>) => void): void; /** * Sets formatting on specified items and data in the table. * @@ -5062,6 +5121,7 @@ declare namespace Office { * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ setFormatsAsync(cellFormat: any[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setFormatsAsync(cellFormat: any[], callback?: (result: AsyncResult) => void): void; /** * Updates table formatting options on the bound table. * @@ -5115,6 +5175,7 @@ declare namespace Office { * */ setTableOptionsAsync(tableOptions: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + setTableOptionsAsync(tableOptions: any, callback?: (result: AsyncResult) => void): void; } /** * Represents the data in a table or a {@link Office.TableBinding}. @@ -8712,6 +8773,7 @@ declare namespace Office { * The body is provided in the requested format in the asyncResult.value property. */ getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8750,6 +8812,7 @@ declare namespace Office { * The content type is returned as one of the CoercionType values in the asyncResult.value property. */ getTypeAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getTypeAsync(callback?: (result: AsyncResult) => void): void; /** * Adds the specified content to the beginning of the item body. * @@ -8784,6 +8847,7 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ prependAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + prependAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Adds the specified content to the beginning of the item body. * @@ -8883,6 +8947,7 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ setAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + setAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Replaces the entire body with the specified text. * @@ -8990,6 +9055,7 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; + setSelectedDataAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Replaces the selection in the body with the specified text. * From 34942ea10b4a1387bc0eaecd30289b2a6107e15d Mon Sep 17 00:00:00 2001 From: Kim Brandl Date: Wed, 2 Jan 2019 13:51:59 -0800 Subject: [PATCH 123/225] Update Word.ContentControl descriptions per OfficeDev/office-js-docs-reference/issues/251. --- types/office-js/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 4c451e9de6..4272bcb1ea 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -49522,7 +49522,7 @@ declare namespace Word { readonly id: number; /** * - * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. + * Gets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * [Api set: WordApi 1.1] */ @@ -49757,7 +49757,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. + * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety. * * [Api set: WordApi 1.1] * @@ -49767,7 +49767,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. + * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety. * * [Api set: WordApi 1.1] * From ac11e4546b5e8cf184508990430be9d51d67e149 Mon Sep 17 00:00:00 2001 From: Kim Brandl Date: Wed, 2 Jan 2019 13:57:23 -0800 Subject: [PATCH 124/225] Update preview d.ts file. --- types/office-js-preview/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 2803e305ff..5e3462a2ce 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -61745,7 +61745,7 @@ declare namespace Word { readonly id: number; /** * - * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. + * Gets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. * * [Api set: WordApi 1.1] */ @@ -61980,7 +61980,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. + * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety. * * [Api set: WordApi 1.1] * @@ -61990,7 +61990,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. + * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before', or 'After'. This method is only supported if the content control encompasses one or more paragraphs in entirety. * * [Api set: WordApi 1.1] * From dd1a1d163c62e9604de88dd63a984ff3d0ffcac8 Mon Sep 17 00:00:00 2001 From: Karol Majewski Date: Mon, 31 Dec 2018 19:32:32 +0100 Subject: [PATCH 125/225] Add definitions for task-worklet --- types/task-worklet/index.d.ts | 36 ++++++++++++++++++++++++ types/task-worklet/task-worklet-tests.ts | 23 +++++++++++++++ types/task-worklet/tsconfig.json | 24 ++++++++++++++++ types/task-worklet/tslint.json | 1 + 4 files changed, 84 insertions(+) create mode 100644 types/task-worklet/index.d.ts create mode 100644 types/task-worklet/task-worklet-tests.ts create mode 100644 types/task-worklet/tsconfig.json create mode 100644 types/task-worklet/tslint.json diff --git a/types/task-worklet/index.d.ts b/types/task-worklet/index.d.ts new file mode 100644 index 0000000000..add9b1b3dc --- /dev/null +++ b/types/task-worklet/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for task-worklet 0.1 +// Project: https://github.com/GoogleChromeLabs/task-worklet +// Definitions by: Karol Majewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare class TaskQueue { + constructor(options?: Options); + postTask(taskName: U['name'], ...args: Parameters): Task>; + addModule(moduleURL: string): Promise; +} + +interface Options { + size?: number; +} + +interface TaskDescriptor { + name: string; + (...args: any): any; +} + +export interface Task { + id: number; + state: State; + result: Promise; +} + +export type State = + | 'cancelled' + | 'completed' + | 'fulfilled' + | 'pending' + | 'scheduled'; + +export default TaskQueue; +export as namespace TaskQueue; diff --git a/types/task-worklet/task-worklet-tests.ts b/types/task-worklet/task-worklet-tests.ts new file mode 100644 index 0000000000..30a5072a2b --- /dev/null +++ b/types/task-worklet/task-worklet-tests.ts @@ -0,0 +1,23 @@ +import TaskQueue, { Task, State } from 'task-worklet'; + +interface Fetcher { + name: 'fetch'; + (input: RequestInfo, init?: RequestInit): Promise; +} + +const unsafe = new TaskQueue(); // $ExpectType TaskQueue +const withEmptyOptions = new TaskQueue({}); // $ExpectType TaskQueue +const withValidOptions = new TaskQueue({ size: 2 }); // $ExpectType TaskQueue + +const queue = new TaskQueue(); // $ExpectType TaskQueue +queue.addModule('/fetcher-worklet.js'); // $ExpectType Promise +const task = queue.postTask('fetch', 'https://example.com'); // $ExpectType Task> + +async () => { + const result = await task.result; // $ExpectType Response + const id = task.id; // $ExpectType number + const state = task.state; // $ExpectType State +}; + +new TaskQueue({ size: 1, excessProperty: true }); // $ExpectError +queue.postTask('incorrect-task-name'); // $ExpectError diff --git a/types/task-worklet/tsconfig.json b/types/task-worklet/tsconfig.json new file mode 100644 index 0000000000..4697c07f30 --- /dev/null +++ b/types/task-worklet/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "task-worklet-tests.ts" + ] +} diff --git a/types/task-worklet/tslint.json b/types/task-worklet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/task-worklet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0e4eb7633c0a86dd2d32ca8d3b9925e34e1572a6 Mon Sep 17 00:00:00 2001 From: Karol Majewski Date: Mon, 31 Dec 2018 20:32:24 +0100 Subject: [PATCH 126/225] Bump up the required version of TypeScript --- types/task-worklet/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/task-worklet/index.d.ts b/types/task-worklet/index.d.ts index add9b1b3dc..e1c68ffd84 100644 --- a/types/task-worklet/index.d.ts +++ b/types/task-worklet/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/GoogleChromeLabs/task-worklet // Definitions by: Karol Majewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.1 declare class TaskQueue { constructor(options?: Options); From 50523db106db67cb488d1c587155cecdcd9fa7f2 Mon Sep 17 00:00:00 2001 From: Karol Majewski Date: Mon, 31 Dec 2018 23:27:20 +0100 Subject: [PATCH 127/225] Offer different version for TypeScript >3.1 --- types/task-worklet/index.d.ts | 13 +++----- types/task-worklet/package.json | 14 +++++++++ types/task-worklet/task-worklet-tests.ts | 12 ++++---- types/task-worklet/ts3.1/index.d.ts | 30 +++++++++++++++++++ .../task-worklet/ts3.1/task-worklet-tests.ts | 23 ++++++++++++++ types/task-worklet/ts3.1/tsconfig.json | 24 +++++++++++++++ types/task-worklet/ts3.1/tslint.json | 1 + 7 files changed, 102 insertions(+), 15 deletions(-) create mode 100644 types/task-worklet/package.json create mode 100644 types/task-worklet/ts3.1/index.d.ts create mode 100644 types/task-worklet/ts3.1/task-worklet-tests.ts create mode 100644 types/task-worklet/ts3.1/tsconfig.json create mode 100644 types/task-worklet/ts3.1/tslint.json diff --git a/types/task-worklet/index.d.ts b/types/task-worklet/index.d.ts index e1c68ffd84..69e52bf4ef 100644 --- a/types/task-worklet/index.d.ts +++ b/types/task-worklet/index.d.ts @@ -2,11 +2,11 @@ // Project: https://github.com/GoogleChromeLabs/task-worklet // Definitions by: Karol Majewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.1 +// TypeScript Version: 2.9 -declare class TaskQueue { +declare class TaskQueue { constructor(options?: Options); - postTask(taskName: U['name'], ...args: Parameters): Task>; + postTask(taskName: string, ...args: any[]): Task; addModule(moduleURL: string): Promise; } @@ -14,12 +14,7 @@ interface Options { size?: number; } -interface TaskDescriptor { - name: string; - (...args: any): any; -} - -export interface Task { +export interface Task { id: number; state: State; result: Promise; diff --git a/types/task-worklet/package.json b/types/task-worklet/package.json new file mode 100644 index 0000000000..49b3fec869 --- /dev/null +++ b/types/task-worklet/package.json @@ -0,0 +1,14 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + }, + "dependencies": { + "typescript": ">2.9.0" + } +} diff --git a/types/task-worklet/task-worklet-tests.ts b/types/task-worklet/task-worklet-tests.ts index 30a5072a2b..c4abfe898b 100644 --- a/types/task-worklet/task-worklet-tests.ts +++ b/types/task-worklet/task-worklet-tests.ts @@ -5,16 +5,16 @@ interface Fetcher { (input: RequestInfo, init?: RequestInit): Promise; } -const unsafe = new TaskQueue(); // $ExpectType TaskQueue -const withEmptyOptions = new TaskQueue({}); // $ExpectType TaskQueue -const withValidOptions = new TaskQueue({ size: 2 }); // $ExpectType TaskQueue +const unsafe = new TaskQueue(); // $ExpectType TaskQueue +const withEmptyOptions = new TaskQueue({}); // $ExpectType TaskQueue +const withValidOptions = new TaskQueue({ size: 2 }); // $ExpectType TaskQueue -const queue = new TaskQueue(); // $ExpectType TaskQueue +const queue = new TaskQueue(); // $ExpectType TaskQueue queue.addModule('/fetcher-worklet.js'); // $ExpectType Promise -const task = queue.postTask('fetch', 'https://example.com'); // $ExpectType Task> +const task = queue.postTask('fetch', 'https://example.com'); // $ExpectType Task async () => { - const result = await task.result; // $ExpectType Response + const result = await task.result; // $ExpectType any const id = task.id; // $ExpectType number const state = task.state; // $ExpectType State }; diff --git a/types/task-worklet/ts3.1/index.d.ts b/types/task-worklet/ts3.1/index.d.ts new file mode 100644 index 0000000000..158b9b40af --- /dev/null +++ b/types/task-worklet/ts3.1/index.d.ts @@ -0,0 +1,30 @@ +declare class TaskQueue { + constructor(options?: Options); + postTask(taskName: U['name'], ...args: Parameters): Task>; + addModule(moduleURL: string): Promise; +} + +interface Options { + size?: number; +} + +interface TaskDescriptor { + name: string; + (...args: any): any; +} + +export interface Task { + id: number; + state: State; + result: Promise; +} + +export type State = + | 'cancelled' + | 'completed' + | 'fulfilled' + | 'pending' + | 'scheduled'; + +export default TaskQueue; +export as namespace TaskQueue; diff --git a/types/task-worklet/ts3.1/task-worklet-tests.ts b/types/task-worklet/ts3.1/task-worklet-tests.ts new file mode 100644 index 0000000000..30a5072a2b --- /dev/null +++ b/types/task-worklet/ts3.1/task-worklet-tests.ts @@ -0,0 +1,23 @@ +import TaskQueue, { Task, State } from 'task-worklet'; + +interface Fetcher { + name: 'fetch'; + (input: RequestInfo, init?: RequestInit): Promise; +} + +const unsafe = new TaskQueue(); // $ExpectType TaskQueue +const withEmptyOptions = new TaskQueue({}); // $ExpectType TaskQueue +const withValidOptions = new TaskQueue({ size: 2 }); // $ExpectType TaskQueue + +const queue = new TaskQueue(); // $ExpectType TaskQueue +queue.addModule('/fetcher-worklet.js'); // $ExpectType Promise +const task = queue.postTask('fetch', 'https://example.com'); // $ExpectType Task> + +async () => { + const result = await task.result; // $ExpectType Response + const id = task.id; // $ExpectType number + const state = task.state; // $ExpectType State +}; + +new TaskQueue({ size: 1, excessProperty: true }); // $ExpectError +queue.postTask('incorrect-task-name'); // $ExpectError diff --git a/types/task-worklet/ts3.1/tsconfig.json b/types/task-worklet/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e5076ca083 --- /dev/null +++ b/types/task-worklet/ts3.1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "task-worklet-tests.ts" + ] +} diff --git a/types/task-worklet/ts3.1/tslint.json b/types/task-worklet/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/task-worklet/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 336e93f3bc77af25c7a81c4ebacd949fdd12af96 Mon Sep 17 00:00:00 2001 From: Karol Majewski Date: Wed, 2 Jan 2019 23:40:37 +0100 Subject: [PATCH 128/225] Use the correct repository URL --- types/task-worklet/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/task-worklet/index.d.ts b/types/task-worklet/index.d.ts index 69e52bf4ef..05128aa465 100644 --- a/types/task-worklet/index.d.ts +++ b/types/task-worklet/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for task-worklet 0.1 -// Project: https://github.com/GoogleChromeLabs/task-worklet +// Project: https://github.com/developit/task-worklet // Definitions by: Karol Majewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 From e78fdc6308cd81ddb03ee96ed5b08db333dd84d3 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 2 Jan 2019 14:46:48 -0800 Subject: [PATCH 129/225] Fixing capitalization and removing redundant Outlook overloads --- types/office-js-preview/index.d.ts | 22 +++++++++++----------- types/office-js/index.d.ts | 27 +++++++++++---------------- 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 7e677c7ed4..dec070dad5 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -3571,8 +3571,8 @@ declare namespace Office { * This is returned in the data structure or format you specified with the coercionType parameter. * (See Remarks for more information about data coercion.) */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; - getSelectedDataAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. * @@ -8764,7 +8764,7 @@ declare namespace Office { * * In addition to this signature, this method also has the following signature: * - * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` + * `getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void;` * * @param coercionType The format for the returned body. * @param options Optional. An object literal that contains one or more of the following properties: @@ -8772,7 +8772,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAsync(coercionType: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8793,7 +8793,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Gets a value that indicates whether the content is in HTML or text format. @@ -10276,7 +10276,7 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -10302,7 +10302,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. * @@ -12207,7 +12207,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -12235,7 +12235,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Removes an attachment from a message or appointment. * @@ -13679,7 +13679,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -13707,7 +13707,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 200008fda5..6468bbfffa 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -3571,8 +3571,8 @@ declare namespace Office { * This is returned in the data structure or format you specified with the coercionType parameter. * (See Remarks for more information about data coercion.) */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; - getSelectedDataAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options?: GetSelectedDataOptions, callback?: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback?: (result: AsyncResult) => void): void; /** * Goes to the specified object or location in the document. * @@ -8764,7 +8764,7 @@ declare namespace Office { * * In addition to this signature, this method also has the following signature: * - * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` + * `getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void;` * * @param coercionType The format for the returned body. * @param options Optional. An object literal that contains one or more of the following properties: @@ -8772,8 +8772,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - getAsync(coerciontype: Office.CoercionType, callback?: (result: AsyncResult) => void): void; + getAsync(coercionType: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8794,7 +8793,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Gets a value that indicates whether the content is in HTML or text format. @@ -8812,7 +8811,6 @@ declare namespace Office { * The content type is returned as one of the CoercionType values in the asyncResult.value property. */ getTypeAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; - getTypeAsync(callback?: (result: AsyncResult) => void): void; /** * Adds the specified content to the beginning of the item body. * @@ -8847,7 +8845,6 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ prependAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; - prependAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Adds the specified content to the beginning of the item body. * @@ -8947,7 +8944,6 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ setAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; - setAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Replaces the entire body with the specified text. * @@ -9055,7 +9051,6 @@ declare namespace Office { * Any errors encountered will be provided in the asyncResult.error property. */ setSelectedDataAsync(data: string, options?: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (result: AsyncResult) => void): void; - setSelectedDataAsync(data: string, callback?: (result: AsyncResult) => void): void; /** * Replaces the selection in the body with the specified text. * @@ -10281,7 +10276,7 @@ declare namespace Office { * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -10307,7 +10302,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. * @@ -12212,7 +12207,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -12240,7 +12235,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Removes an attachment from a message or appointment. * @@ -13684,7 +13679,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Asynchronously returns selected data from the subject or body of a message. * @@ -13712,7 +13707,7 @@ declare namespace Office { * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. */ - getSelectedDataAsync(coerciontype: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; + getSelectedDataAsync(coercionType: Office.CoercionType, options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. * From 1f023ca641b7e876e3f7ebcd0e623f3561f94f53 Mon Sep 17 00:00:00 2001 From: Ben Date: Wed, 2 Jan 2019 19:57:52 -0500 Subject: [PATCH 130/225] change default export to export = --- types/raf/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/raf/index.d.ts b/types/raf/index.d.ts index 1cab1a2fc8..e954bc5540 100644 --- a/types/raf/index.d.ts +++ b/types/raf/index.d.ts @@ -7,6 +7,6 @@ declare const raf: { (callback: (timestamp: number) => void): number; cancel: (handle: number) => void; polyfill: (globalObject?: any) => void; -}; +} -export default raf; +export = raf; From 6da80ae61a54c491e9e66c437a69f1544a64c952 Mon Sep 17 00:00:00 2001 From: Bryan Spears Date: Wed, 2 Jan 2019 18:34:28 -0700 Subject: [PATCH 131/225] [needle] Export all types --- types/needle/index.d.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/types/needle/index.d.ts b/types/needle/index.d.ts index b9c07b320b..fae0a01392 100644 --- a/types/needle/index.d.ts +++ b/types/needle/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for needle 2.0 // Project: https://github.com/tomas/needle -// Definitions by: San Chen , Niklas Mollenhauer , Matanel Sindilevich +// Definitions by: San Chen , +// Niklas Mollenhauer , +// Matanel Sindilevich , +// Bryan Spears // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -240,11 +243,11 @@ declare function needle(method: core.NeedleReadonlyHttpVerbs, url: string, optio declare function needle(method: core.NeedleHttpVerbs, url: string, data: core.BodyData, options?: core.NeedleOptions): Promise; declare namespace needle { - type BodyData = core.BodyData; - type NeedleCallback = core.NeedleCallback; - type NeedleHttpVerbs = core.NeedleHttpVerbs; + export type BodyData = core.BodyData; + export type NeedleCallback = core.NeedleCallback; + export type NeedleHttpVerbs = core.NeedleHttpVerbs; export type NeedleOptions = core.NeedleOptions; - type ReadableStream = core.ReadableStream; + export type ReadableStream = core.ReadableStream; /** * Lets override the defaults for all future requests. From 4ff739328c9acc3bbdf941cd3e38609350eecebe Mon Sep 17 00:00:00 2001 From: Ben Date: Wed, 2 Jan 2019 21:04:11 -0500 Subject: [PATCH 132/225] fix tests --- types/raf/index.d.ts | 2 +- types/raf/raf-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/raf/index.d.ts b/types/raf/index.d.ts index e954bc5540..d54b1c6e6c 100644 --- a/types/raf/index.d.ts +++ b/types/raf/index.d.ts @@ -7,6 +7,6 @@ declare const raf: { (callback: (timestamp: number) => void): number; cancel: (handle: number) => void; polyfill: (globalObject?: any) => void; -} +}; export = raf; diff --git a/types/raf/raf-tests.ts b/types/raf/raf-tests.ts index d57019913d..c3da3cbd01 100644 --- a/types/raf/raf-tests.ts +++ b/types/raf/raf-tests.ts @@ -1,4 +1,4 @@ -import raf from "raf"; +import * as raf from "raf"; const handle = raf((timestamp) => { timestamp; // $ExpectType number From 2129015369c3a0c29508ef69d1118935ceb54a23 Mon Sep 17 00:00:00 2001 From: Sindre Moen Date: Thu, 3 Jan 2019 07:57:28 +0100 Subject: [PATCH 133/225] Remove myself from Mongoose v4 contributors --- types/mongoose/v4/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index d8a9feb085..e38317ae5d 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Mongoose 4.7.1 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak +// Definitions by: simonxca , horiuchi , lukasz-zak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From 796d89f6d1fe1fb995180eb6e4ef053ebd0ad2bc Mon Sep 17 00:00:00 2001 From: Sindre Moen Date: Thu, 3 Jan 2019 07:59:32 +0100 Subject: [PATCH 134/225] Remove myself from Mongoose contributors --- types/mongoose/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b588b4ecef..14e965dd5f 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,7 +1,6 @@ // Type definitions for Mongoose 5.3.4 // Project: http://mongoosejs.com/ // Definitions by: horiuchi -// sindrenm // lukasz-zak // Alorel // jendrikw From 4ac28861b9c93da1f4a8e0a64c9412f302ce4d49 Mon Sep 17 00:00:00 2001 From: Mats Roshauw Date: Thu, 3 Jan 2019 10:12:19 +0100 Subject: [PATCH 135/225] Add closeOnBlur property to WrapperProps --- types/react-aria-menubutton/index.d.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/types/react-aria-menubutton/index.d.ts b/types/react-aria-menubutton/index.d.ts index 3bfc68259e..157fdff642 100644 --- a/types/react-aria-menubutton/index.d.ts +++ b/types/react-aria-menubutton/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-aria-menubutton 5.1 +// Type definitions for react-aria-menubutton 6.1 // Project: https://github.com/davidtheclark/react-aria-menubutton // Definitions by: Muhammad Fawwaz Orabi // Chris Rohlfs +// Mats Roshauw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -33,6 +34,13 @@ export interface WrapperProps */ closeOnSelection?: boolean; + /** + * By default, it does automatically close. + * If false, the menu will not automatically close when it + * blurs. Default: `true`. + */ + closeOnBlur?: boolean; + isOpen?: boolean; tag?: T["tagName"]; From 26284942785bd43500772a29607fb2b4d6d53904 Mon Sep 17 00:00:00 2001 From: Sameer KC Date: Thu, 3 Jan 2019 10:13:21 +0100 Subject: [PATCH 136/225] Deleting unnecessary file --- node-gettext/conf/tslint.json | 1 - 1 file changed, 1 deletion(-) delete mode 100644 node-gettext/conf/tslint.json diff --git a/node-gettext/conf/tslint.json b/node-gettext/conf/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/node-gettext/conf/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From 11ecd41a0be531c54b2f3fb44a53dc645d820d21 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Thu, 3 Jan 2019 10:16:55 +0100 Subject: [PATCH 137/225] Improve type of message payload and sendTo return type --- types/iobroker/index.d.ts | 24 +++++++++-------- types/iobroker/iobroker-tests.ts | 45 +++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 4cfbddc2a2..b83c89017f 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -828,10 +828,12 @@ declare global { ca: Array; } + type MessagePayload = string | Record; + /** Callback information for a passed message */ interface MessageCallbackInfo { /** The original message payload */ - message: string | object; + message: MessagePayload; /** ID of this callback */ id: number; // ??? @@ -839,14 +841,13 @@ declare global { /** Timestamp of this message */ time: number; } - type MessageCallback = (result?: any) => void; /** A message being passed between adapter instances */ interface Message { /** The command to be executed */ command: string; /** The message payload */ - message: string | object; + message: MessagePayload; /** The source of this message */ from: string; /** ID of this message */ @@ -1038,8 +1039,8 @@ declare global { * @param command (optional) Command name of the target instance. Default: "send" * @param message The message (e.g. params) to send. */ - sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; /** * Sends a message to a specific instance or all instances of some specific adapter. * @param instanceName The instance to send this message to. @@ -1048,18 +1049,18 @@ declare global { * @param command (optional) Command name of the target instance. Default: "send" * @param message The message (e.g. params) to send. */ - sendToAsync(instanceName: string, message: string | object): Promise; - sendToAsync(instanceName: string, command: string, message: string | object): Promise; + sendToAsync(instanceName: string, message: MessagePayload): Promise; + sendToAsync(instanceName: string, command: string, message: MessagePayload): Promise; /** * Sends a message to a specific host or all hosts. */ - sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; /** * Sends a message to a specific host or all hosts. */ - sendToHostAsync(hostName: string, message: string | object): Promise; - sendToHostAsync(hostName: string, command: string, message: string | object): Promise; + sendToHostAsync(hostName: string, message: MessagePayload): Promise; + sendToHostAsync(hostName: string, command: string, message: MessagePayload): Promise; /** Convert ID to {device: D, channel: C, state: S} */ idToDCS(id: string): { @@ -1584,6 +1585,7 @@ declare global { type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void; type StateChangeHandler = (id: string, obj: State | null | undefined) => void; type MessageHandler = (obj: Message) => void; + type MessageCallback = (response?: Message) => void; type UnloadHandler = (callback: EmptyCallback) => void; type EmptyCallback = () => void; diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 2ee7da83d5..f49eb34576 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -99,7 +99,8 @@ function messageHandler(msg: ioBroker.Message) { msg.callback.time.toFixed(); msg.command.toLowerCase(); msg.from.toLowerCase(); - msg.message.toString(); + typeof msg.message === "object" && msg.message.anything; + typeof msg.message === "string" && msg.message.toLowerCase(); } function unloadHandler(callback: ioBroker.EmptyCallback) { @@ -198,3 +199,45 @@ switch (adapter.log.level) { default: assertNever(adapter.log.level); } + +adapter.sendTo("foo.0", "command", "message"); +adapter.sendTo("foo.0", "message"); +adapter.sendTo("foo.0", "command", {msg: "message"}); +adapter.sendTo("foo.0", {msg: "message"}); + +function handleMessageResponse(response?: ioBroker.Message) { + if (!response) return; + response._id.toFixed(); + response.callback.ack.valueOf(); + response.callback.id.toFixed(); + response.callback.message.toString(); + response.callback.time.toFixed(); + response.command.toLowerCase(); + response.from.toLowerCase(); + typeof response.message === "object" && response.message.anything; + typeof response.message === "string" && response.message.toLowerCase(); +} +adapter.sendTo("foo.0", "command", "message", handleMessageResponse); +adapter.sendTo("foo.0", "message", handleMessageResponse); +adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse); +adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse); + +adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse); +adapter.sendToAsync("foo.0", "message").then(handleMessageResponse); +adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse); +adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse); + +adapter.sendToHost("host-foo", "command", "message"); +adapter.sendToHost("host-foo", "message"); +adapter.sendToHost("host-foo", "command", {msg: "message"}); +adapter.sendToHost("host-foo", {msg: "message"}); + +adapter.sendToHost("host-foo", "command", "message", handleMessageResponse); +adapter.sendToHost("host-foo", "message", handleMessageResponse); +adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse); +adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse); + +adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); From 3bdd3c10f378194e818b318b352b1418a1417488 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Thu, 3 Jan 2019 10:31:31 +0100 Subject: [PATCH 138/225] MessageCallback should be where the other callbacks are --- types/iobroker/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index b83c89017f..81381d801d 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1585,7 +1585,6 @@ declare global { type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void; type StateChangeHandler = (id: string, obj: State | null | undefined) => void; type MessageHandler = (obj: Message) => void; - type MessageCallback = (response?: Message) => void; type UnloadHandler = (callback: EmptyCallback) => void; type EmptyCallback = () => void; @@ -1593,6 +1592,8 @@ declare global { // TODO: Redefine callbacks as subclass of GenericCallback type GenericCallback = (err: string | null, result?: T) => void; + type MessageCallback = (response?: Message) => void; + type SetObjectCallback = (err: string | null, obj: { id: string }) => void; type GetObjectCallback = (err: string | null, obj: ioBroker.Object | null | undefined) => void; type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; From 5731953945ec2d03797a33cab0e8f32d79fa232b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= Date: Thu, 3 Jan 2019 12:05:54 +0200 Subject: [PATCH 139/225] fix: review --- types/socketcluster-server/index.d.ts | 2 +- types/socketcluster-server/scserver.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/socketcluster-server/index.d.ts b/types/socketcluster-server/index.d.ts index 7466d1daed..17f138bf0f 100644 --- a/types/socketcluster-server/index.d.ts +++ b/types/socketcluster-server/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for socketcluster-server 13.1 +// Type definitions for socketcluster-server 14.2 // Project: https://github.com/SocketCluster/socketcluster-server // Definitions by: Daniel Rose // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts index cef90acfed..48952a8a8a 100644 --- a/types/socketcluster-server/scserver.d.ts +++ b/types/socketcluster-server/scserver.d.ts @@ -34,7 +34,7 @@ declare class SCServer extends EventEmitter { on(event: "connection", listener: SCServer.connectionListenerFunction): this; on(event: "ready", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; + on(event: "warning" | "error", listener: (error: Error) => void): this; on(event: "disconnection" | "connectionAbort" | "closure", listener: SCServer.disconnectionListenerFunction): this; on(event: "subscription", listener: SCServer.subscriptionListenerFunction): this; on(event: "unsubscription", listener: SCServer.unsubscriptionListenerFunction): this; @@ -323,7 +323,7 @@ declare namespace SCServer { type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; type disconnectionListenerFunction = (scSocket: SCServerSocket, code: number, data: any) => void; type subscriptionListenerFunction = (scSocket: SCServerSocket, name: string, options: {channel: string}) => void; - type unsubscriptionListenerFunction = (scSocket: SCServerSocket, name: string, channel: string) => void; + type unsubscriptionListenerFunction = (scSocket: SCServerSocket, channel: string) => void; type handshakeListenerFunction = (scSocket: SCServerSocket) => void; type badSocketAuthTokenListenerFunction = (scSocket: SCServerSocket, status: badAuthStatus) => void; From 9c1c7e78a9a2b4af8e2cda842c3693f67bb9e42d Mon Sep 17 00:00:00 2001 From: Cheng Wang Date: Thu, 3 Jan 2019 18:29:31 +0800 Subject: [PATCH 140/225] react-router fix (#31853) * [react-router] redirectLocation is not DOM Location type should use Location type from history package. see https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#match-routes-location-history-options--cb * [react-router] export argument types of match --- types/react-router/v3/index.d.ts | 2 +- types/react-router/v3/lib/match.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-router/v3/index.d.ts b/types/react-router/v3/index.d.ts index c21afeb049..2c624a63ab 100644 --- a/types/react-router/v3/index.d.ts +++ b/types/react-router/v3/index.d.ts @@ -55,7 +55,7 @@ export { default as Route } from "react-router/lib/Route"; export { createRoutes } from "react-router/lib/RouteUtils"; export { default as RouterContext } from "react-router/lib/RouterContext"; export { routerShape, locationShape } from "react-router/lib/PropTypes"; -export { default as match } from "react-router/lib/match"; +export { default as match, MatchHistoryArgs, MatchLocationArgs, MatchCallback } from "react-router/lib/match"; export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; export { formatPattern } from "react-router/lib/PatternUtils"; export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; diff --git a/types/react-router/v3/lib/match.d.ts b/types/react-router/v3/lib/match.d.ts index 77a35afafd..eb19888e0a 100644 --- a/types/react-router/v3/lib/match.d.ts +++ b/types/react-router/v3/lib/match.d.ts @@ -1,4 +1,4 @@ -import { Basename, History, LocationDescriptor } from "history"; +import { Basename, History, Location, LocationDescriptor } from "history"; import { ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; export interface MatchArgs { From 4a45db244e4ae598bfc109da0697a652ec0e6a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luka=CC=81s=CC=8C=20Havli=CC=81c=CC=8Cek?= Date: Thu, 3 Jan 2019 13:42:25 +0100 Subject: [PATCH 141/225] React Native - added missing property (legacyImplementation) for SectionList --- types/react-native/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 865a46eefa..6a6db87b54 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -4269,6 +4269,8 @@ export interface SectionListProps extends VirtualizedListWithoutRenderIte * Only enabled by default on iOS because that is the platform standard there. */ stickySectionHeadersEnabled?: boolean; + + legacyImplementation?: boolean; } export interface SectionListScrollParams { From 2f2146a324a4667cd4f669caaf158b06a89bff30 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Thu, 3 Jan 2019 14:34:30 +0100 Subject: [PATCH 142/225] Remove tslint rule overrides and fix resulting issues. The 'ban-types' rule has not been removed because required changes conflict with other declarations (mongodb?). --- types/mongoose-paginate-v2/index.d.ts | 45 +++++------ .../mongoose-paginate-v2-tests.ts | 17 ++--- types/mongoose-paginate-v2/tslint.json | 75 +------------------ 3 files changed, 28 insertions(+), 109 deletions(-) diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index 3c178c5908..dfd70cc0cb 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mongoose-paginate-v2 1.0.13 +// Type definitions for mongoose-paginate-v2 1.0 // Project: https://github.com/aravindnc/mongoose-paginate-v2 // Definitions by: Linus Brolin // simonxca @@ -8,25 +8,23 @@ // // Based on type declarations for mongoose-paginate 5.0.0. -/// - declare module 'mongoose' { - export interface CustomLabels { - totalDocs?: string, - limit?: string, - page?: string, - totalPages?: string, - docs?: string, - nextPage?: string, - prevPage?: string, + interface CustomLabels { + totalDocs?: string; + limit?: string; + page?: string; + totalPages?: string; + docs?: string; + nextPage?: string; + prevPage?: string; } - export interface PaginateOptions { + interface PaginateOptions { select?: Object | string; sort?: Object | string; - customLabels?: CustomLabels, - collation?: CollationOptions, - populate?: Array | Array | Object | string; + customLabels?: CustomLabels; + collation?: CollationOptions; + populate?: Object[] | string[] | Object | string; lean?: boolean; leanWithId?: boolean; offset?: number; @@ -34,29 +32,26 @@ declare module 'mongoose' { limit?: number; } - export interface PaginateResult { - docs: Array; + interface PaginateResult { + docs: T[]; total: number; limit: number; page?: number; pages?: number; offset?: number; - [customLabel: string]: Array | number | undefined; + [customLabel: string]: T[] | number | undefined; } interface PaginateModel extends Model { - paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; + paginate(query?: object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; } - export function model( + function model( name: string, schema?: Schema, collection?: string, skipInit?: boolean): PaginateModel; } -declare module 'mongoose-paginate-v2' { - import mongoose = require('mongoose'); - var _: (schema: mongoose.Schema) => void; - export = _; -} +import mongoose = require('mongoose'); +export function _(schema: mongoose.Schema): void; diff --git a/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts index 8410c740e5..200ca4e12a 100644 --- a/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts +++ b/types/mongoose-paginate-v2/mongoose-paginate-v2-tests.ts @@ -13,7 +13,6 @@ import { import mongoosePaginate = require('mongoose-paginate'); import { Router, Request, Response } from 'express'; - //#region Test Models interface User extends Document { email: string; @@ -29,20 +28,19 @@ const UserSchema: Schema = new Schema({ UserSchema.plugin(mongoosePaginate); -interface UserModel extends PaginateModel {}; +interface UserModel extends PaginateModel {} -let UserModel: UserModel = model('User', UserSchema) as UserModel; +const UserModel: UserModel = model('User', UserSchema) as UserModel; //#endregion - //#region Test Paginate -let router: Router = Router(); +const router: Router = Router(); -router.get('/users.json', function(req: Request, res: Response) { - let descending: boolean = true; - let options: PaginateOptions = {} as PaginateOptions; +router.get('/users.json', (req: Request, res: Response) => { + const descending = true; + const options: PaginateOptions = {}; options.select = 'email username'; - options.sort = { 'username': (descending ? -1 : 1) }; + options.sort = { username: (descending ? -1 : 1) }; options.collation = { locale: 'en_US', strength: 1 }; options.populate = ''; options.lean = true; @@ -78,6 +76,5 @@ router.get('/users.json', function(req: Request, res: Response) { console.dir(value.docsCustom); return res.json(value); }); - }); //#endregion diff --git a/types/mongoose-paginate-v2/tslint.json b/types/mongoose-paginate-v2/tslint.json index a41bf5d19a..a62d0d4e68 100644 --- a/types/mongoose-paginate-v2/tslint.json +++ b/types/mongoose-paginate-v2/tslint.json @@ -1,79 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "ban-types": false } } From 581bcc1903f76eabd1f2ff5d2724b2f3fc03c1b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luka=CC=81s=CC=8C=20Havli=CC=81c=CC=8Cek?= Date: Thu, 3 Jan 2019 14:40:12 +0100 Subject: [PATCH 143/225] React Native - added missing docs --- types/react-native/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 6a6db87b54..2c3922b89d 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3994,6 +3994,9 @@ export interface FlatListProps extends VirtualizedListProps { */ keyExtractor?: (item: ItemT, index: number) => string; + /** + * Uses legacy MetroListView instead of default VirtualizedSectionList + */ legacyImplementation?: boolean; /** @@ -4269,7 +4272,10 @@ export interface SectionListProps extends VirtualizedListWithoutRenderIte * Only enabled by default on iOS because that is the platform standard there. */ stickySectionHeadersEnabled?: boolean; - + + /** + * Uses legacy MetroListView instead of default VirtualizedSectionList + */ legacyImplementation?: boolean; } From dc1aa97bd1847f789f8bb7b21bc3526b8df35e88 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Thu, 3 Jan 2019 15:49:40 +0200 Subject: [PATCH 144/225] Add better documentation blocks. --- types/linkifyjs/linkifyjs-tests.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx index 23ae8e3722..02d9d3b6d5 100644 --- a/types/linkifyjs/linkifyjs-tests.tsx +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -5,7 +5,10 @@ import Linkify from "linkifyjs/react"; declare function describe(desc: string, f: () => void): void; describe("linkifyjs/html", () => { - // From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html + /** + * The following tests were taken directly from the documentation: + * https://soapbox.github.io/linkifyjs/docs/options.html + */ /* attributes */ @@ -147,7 +150,10 @@ describe("linkifyjs/html", () => { }); describe("linkifyjs/react", () => { - // From the docs here: https://soapbox.github.io/linkifyjs/docs/linkify-react.html + /** + * The following tests were taken directly from the documentation: + * https://soapbox.github.io/linkifyjs/docs/linkify-react.html + */ /* Usage */ @@ -178,7 +184,9 @@ describe("linkifyjs/react", () => { {content}; } - /* A few more test cases */ + /** + * The following tests were made specifically for DefinitelyTyped. + */ /* Default values for all props */ { From 6637b2df5e2620fb4d0b39a77abec4cf09d17288 Mon Sep 17 00:00:00 2001 From: s8kggu_zlatkoa Date: Thu, 3 Jan 2019 15:33:07 +0100 Subject: [PATCH 145/225] Added type definitions for is-valid-path. --- types/is-valid-path/index.d.ts | 8 ++++++++ types/is-valid-path/is-valid-path-tests.ts | 18 +++++++++++++++++ types/is-valid-path/tsconfig.json | 23 ++++++++++++++++++++++ types/is-valid-path/tslint.json | 1 + 4 files changed, 50 insertions(+) create mode 100644 types/is-valid-path/index.d.ts create mode 100644 types/is-valid-path/is-valid-path-tests.ts create mode 100644 types/is-valid-path/tsconfig.json create mode 100644 types/is-valid-path/tslint.json diff --git a/types/is-valid-path/index.d.ts b/types/is-valid-path/index.d.ts new file mode 100644 index 0000000000..2aa54e3e99 --- /dev/null +++ b/types/is-valid-path/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-valid-path 0.1 +// Project: https://github.com/jonschlinkert/is-valid-path +// Definitions by: Zlatko Andonovski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isValidPath(path?: string | null): boolean; + +export = isValidPath; diff --git a/types/is-valid-path/is-valid-path-tests.ts b/types/is-valid-path/is-valid-path-tests.ts new file mode 100644 index 0000000000..a0ca7ac1a9 --- /dev/null +++ b/types/is-valid-path/is-valid-path-tests.ts @@ -0,0 +1,18 @@ +// Tests are from the NPM README (https://www.npmjs.com/package/is-valid-path). + +import isValid = require('is-valid-path'); + +isValid('abc.js'); +isValid('abc/def/ghi.js'); +isValid('foo.js'); + +isValid(); +isValid(null); +isValid('!foo.js'); +isValid('*.js'); +isValid('**/abc.js'); +isValid('abc/*.js'); +isValid('abc/(aaa|bbb).js'); +isValid('abc/[a-z].js'); +isValid('abc/{a,b}.js'); +isValid('abc/?.js'); diff --git a/types/is-valid-path/tsconfig.json b/types/is-valid-path/tsconfig.json new file mode 100644 index 0000000000..da95d11317 --- /dev/null +++ b/types/is-valid-path/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", + "is-valid-path-tests.ts" + ] +} diff --git a/types/is-valid-path/tslint.json b/types/is-valid-path/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-valid-path/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 35a4efd52beb081a272fb2095f114a007a9cccf6 Mon Sep 17 00:00:00 2001 From: Simon VDB Date: Thu, 3 Jan 2019 16:29:08 +0100 Subject: [PATCH 146/225] add `sort` to StringifyOptions Adds the sort option thats available in the query string package. --- types/query-string/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/query-string/index.d.ts b/types/query-string/index.d.ts index 6e560f57e9..81c10fb086 100644 --- a/types/query-string/index.d.ts +++ b/types/query-string/index.d.ts @@ -33,6 +33,7 @@ export interface StringifyOptions { strict?: boolean; encode?: boolean; arrayFormat?: 'bracket' | 'index' | 'none'; + sort?: ((m: string, n: string) => boolean) | boolean; } /** From 9284ed563bcac4f67cf23b7cf0b73935f18408a5 Mon Sep 17 00:00:00 2001 From: Simon VDB Date: Thu, 3 Jan 2019 16:35:10 +0100 Subject: [PATCH 147/225] Add to contributor list --- types/query-string/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/query-string/index.d.ts b/types/query-string/index.d.ts index 81c10fb086..3eaf34c159 100644 --- a/types/query-string/index.d.ts +++ b/types/query-string/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for query-string 6.1 +// Type definitions for query-string 6.2 // Project: https://github.com/sindresorhus/query-string // Definitions by: Sam Verschueren // Tanguy Krotoff // HuHuanming // Madara Uchiha // Josh Holmer +// Simon Van den Broeck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 From f18132f94b6a66f994666e584e5b34f15a488485 Mon Sep 17 00:00:00 2001 From: Jeremy Forsythe Date: Thu, 3 Jan 2019 11:47:08 -0500 Subject: [PATCH 148/225] [express-slow-down] Add types --- .../express-slow-down-tests.ts | 27 +++++++ types/express-slow-down/index.d.ts | 75 +++++++++++++++++++ types/express-slow-down/tsconfig.json | 23 ++++++ types/express-slow-down/tslint.json | 1 + 4 files changed, 126 insertions(+) create mode 100644 types/express-slow-down/express-slow-down-tests.ts create mode 100644 types/express-slow-down/index.d.ts create mode 100644 types/express-slow-down/tsconfig.json create mode 100644 types/express-slow-down/tslint.json diff --git a/types/express-slow-down/express-slow-down-tests.ts b/types/express-slow-down/express-slow-down-tests.ts new file mode 100644 index 0000000000..46ab215848 --- /dev/null +++ b/types/express-slow-down/express-slow-down-tests.ts @@ -0,0 +1,27 @@ +import SlowDown = require("express-slow-down"); + +const slowerAllDefaults = new SlowDown({}); + +const slowerWithOptions = new SlowDown({ + windowMs: 15 * 60 * 1000, // 15 minutes, + delayAfter: 1, + delayMs: 0, // disabled + skipFailedRequests: false, + skipSuccessfulRequests: true, +}); + +const slowerWithCallbacks = new SlowDown({ + keyGenerator: (req, res) => req.ip, + skip: (req, res) => false, + onLimitReached: (req, res, opts) => {}, +}); + +class MockStore implements SlowDown.Store { + incr(key: string, cb: SlowDown.StoreIncrementCallback) { } + decrement(key: string) { } + resetKey(key: string) { } +} + +const slowerWithStore = new SlowDown({ + store: new MockStore() +}); diff --git a/types/express-slow-down/index.d.ts b/types/express-slow-down/index.d.ts new file mode 100644 index 0000000000..a446ca4f11 --- /dev/null +++ b/types/express-slow-down/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for express-slow-down 1.1 +// Project: https://github.com/nfriedly/express-slow-down +// Definitions by: Jeremy Forsythe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require("express"); + +declare namespace SlowDown { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + interface Store { + incr(key: string, cb: StoreIncrementCallback): void; + decrement(key: string): void; + resetKey(key: string): void; + } + + /** + * express-slow-down options + */ + interface Options { + /** + * How long to keep records of requests in memory. Defaults to `60000` (1 minute) + */ + windowMs?: number; + + /** + * Max number of connections during `windowMs` before starting to delay responses. + * Defaults to `1`. Set to `0` to disable delaying. + */ + delayAfter?: number; + + /** + * How long to delay the response, multiplied by `(number recent hits - delayAfter)`. + * Defaults to `1000` (1 second). Set to `0` to disable delaying. + */ + delayMs?: number; + + /** + * When `true` failed requests (response status >= 400) won't be counted. Defaults to `false`. + */ + skipFailedRequests?: boolean; + + /** + * When `true` successful requests (response status < 400) won't be counted. Defaults to `false`. + */ + skipSuccessfulRequests?: boolean; + + /** + * Function used to generate keys. By default user IP address (`req.ip`) is used. + * Default: `(req, res) => req.ip` + */ + keyGenerator?(req: express.Request, res: express.Response): string; + + /** + * Function used to skip requests. Returning `true` from the function will skip delaying for that request. + * Default: `(req, res) => false` + */ + skip?(req: express.Request, res: express.Response): boolean; + + /** + * Function to execute the first time the limit is reached within `windowMs`. + * Default: `(req, res, opts) => {}` + */ + onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + + /** + * The storage to use when persisting request attempts. By default, the MemoryStore is used. + */ + store?: Store; + } +} + +declare var SlowDown: new (options: SlowDown.Options) => express.RequestHandler; +export = SlowDown; diff --git a/types/express-slow-down/tsconfig.json b/types/express-slow-down/tsconfig.json new file mode 100644 index 0000000000..9973398566 --- /dev/null +++ b/types/express-slow-down/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-slow-down-tests.ts" + ] +} diff --git a/types/express-slow-down/tslint.json b/types/express-slow-down/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-slow-down/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 35692888a460f7c431e3f754edfcbf1a7946423b Mon Sep 17 00:00:00 2001 From: Bryan Spears Date: Thu, 3 Jan 2019 09:56:34 -0700 Subject: [PATCH 149/225] error can also be `null` --- types/needle/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/needle/index.d.ts b/types/needle/index.d.ts index fae0a01392..509e212c6e 100644 --- a/types/needle/index.d.ts +++ b/types/needle/index.d.ts @@ -23,7 +23,7 @@ declare namespace core { type ReadableStream = NodeJS.ReadableStream; - type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + type NeedleCallback = (error: Error | null, response: NeedleResponse, body: any) => void; interface Cookies { [name: string]: any; From 0566178dc9a85249fe7bd9d1bdbcc8a4dac3f7ba Mon Sep 17 00:00:00 2001 From: David Gomes Date: Thu, 3 Jan 2019 17:03:19 +0000 Subject: [PATCH 150/225] Add sqlstring.raw to sqlstring type definitions. --- types/sqlstring/index.d.ts | 1 + types/sqlstring/sqlstring-tests.ts | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/types/sqlstring/index.d.ts b/types/sqlstring/index.d.ts index bf774824e7..3e85850069 100644 --- a/types/sqlstring/index.d.ts +++ b/types/sqlstring/index.d.ts @@ -7,3 +7,4 @@ export function format(sql: string, args: object | any[]): string; export function escape(value: any): string; export function escapeId(value: any, dotQualifier?: boolean): string; +export function raw(sql: string): { toSqlString: () => string }; diff --git a/types/sqlstring/sqlstring-tests.ts b/types/sqlstring/sqlstring-tests.ts index 6d2ef471c7..d6303c3831 100644 --- a/types/sqlstring/sqlstring-tests.ts +++ b/types/sqlstring/sqlstring-tests.ts @@ -29,3 +29,10 @@ const sql6 = const userId4 = 1; const inserts = ["users", "id", userId4]; const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts); + +const userId4 = 1; +const inserts = ["users", "id", userId4]; +const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts); + +var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); +const sql8 = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); From 9975a166869998b7d183e547b857f3dbee99c901 Mon Sep 17 00:00:00 2001 From: David Gomes Date: Thu, 3 Jan 2019 17:09:01 +0000 Subject: [PATCH 151/225] Add sqlstring.raw to sqlstring type definitions. --- types/sqlstring/sqlstring-tests.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/types/sqlstring/sqlstring-tests.ts b/types/sqlstring/sqlstring-tests.ts index d6303c3831..de6fe64a1d 100644 --- a/types/sqlstring/sqlstring-tests.ts +++ b/types/sqlstring/sqlstring-tests.ts @@ -30,9 +30,5 @@ const userId4 = 1; const inserts = ["users", "id", userId4]; const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts); -const userId4 = 1; -const inserts = ["users", "id", userId4]; -const sql7 = SqlString.format("SELECT * FROM ?? WHERE ?? = ?", inserts); - -var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); +const CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); const sql8 = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); From 62adcee7586cb3e197336385fe5333175bc02997 Mon Sep 17 00:00:00 2001 From: Jeremy Forsythe Date: Thu, 3 Jan 2019 12:14:46 -0500 Subject: [PATCH 152/225] [express-rate-limit] Create definitions for v3 --- .../express-rate-limit-tests.ts | 16 +++- types/express-rate-limit/index.d.ts | 81 ++++++++++++++++--- .../v2/express-rate-limit-tests.ts | 39 +++++++++ types/express-rate-limit/v2/index.d.ts | 42 ++++++++++ types/express-rate-limit/v2/tsconfig.json | 26 ++++++ types/express-rate-limit/v2/tslint.json | 1 + 6 files changed, 193 insertions(+), 12 deletions(-) create mode 100644 types/express-rate-limit/v2/express-rate-limit-tests.ts create mode 100644 types/express-rate-limit/v2/index.d.ts create mode 100644 types/express-rate-limit/v2/tsconfig.json create mode 100644 types/express-rate-limit/v2/tslint.json diff --git a/types/express-rate-limit/express-rate-limit-tests.ts b/types/express-rate-limit/express-rate-limit-tests.ts index aa5c51a016..4b94ef6b05 100644 --- a/types/express-rate-limit/express-rate-limit-tests.ts +++ b/types/express-rate-limit/express-rate-limit-tests.ts @@ -3,7 +3,19 @@ import RateLimit = require("express-rate-limit"); const apiLimiter = new RateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, - delayMs: 0 // disabled + headers: false, + skipFailedRequests: false, + skipSuccessfulRequests: true, +}); + +const apiLimiterWithMaxFn = new RateLimit({ + windowMs: 15 * 60 * 1000, + max: () => 5, +}); + +const apiLimiterWithMaxPromiseFn = new RateLimit({ + windowMs: 15 * 60 * 1000, + max: () => Promise.resolve(5), }); const apiLimiterWithMessageObject = new RateLimit({ @@ -17,8 +29,6 @@ const apiLimiterWithMessageObject = new RateLimit({ const createAccountLimiter = new RateLimit({ windowMs: 60 * 60 * 1000, // 1 hour window - delayAfter: 1, // begin slowing down responses after the first request - delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request max: 5, // start blocking after 5 requests message: "Too many accounts created from this IP, please try again after an hour", handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`)) diff --git a/types/express-rate-limit/index.d.ts b/types/express-rate-limit/index.d.ts index b3f074f28d..9d3459e21b 100644 --- a/types/express-rate-limit/index.d.ts +++ b/types/express-rate-limit/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for express-rate-limit 2.9 +// Type definitions for express-rate-limit 3.3 // Project: https://github.com/nfriedly/express-rate-limit -// Definitions by: Cyril Schumacher , makepost +// Definitions by: Cyril Schumacher +// makepost +// Jeremy Forsythe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -21,19 +23,80 @@ declare namespace RateLimit { [key: string]: any; } + type MaxValueFn = () => number | Promise; + interface Options { - delayAfter?: number; - delayMs?: number; + /** + * The funciton to handle requests once `max` is exceeded. It receives the request and response objects. + * The "next" param is available if you need to pass to the next middleware. The `req.rateLimit` object + * has `limit`, `current`, and `remaining` number of requests, and if the store provides it, a `resetTime` + * Date object. + * Default: `(req, res, next) => res.status(options.statusCode).send(options.message)` + */ handler?(req: express.Request, res: express.Response, next: express.NextFunction): any; + + /** + * Enable headers for request limit (`X-RateLimit-Limit`) and current usage (`X-RateLimit-Remaining`) on all + * responses andtime to wait before retrying (`Retry-After`) when `max` is exceeded. Defaults to `true`. + */ headers?: boolean; + + /** + * Function used to generate keys. Defaults to using `req.ip`. + * Default: `(req, res) => req.ip` + */ keyGenerator?(req: express.Request, res: express.Response): string; - max?: number; + + /** + * Max number of connections during `windowMs` before sending a 429 response. May be a `number` or + * a function that returns a `number` or a `Promise`. Defaults to `5`. Set to `0` to disable. + */ + max?: number | MaxValueFn; + + /** + * Error message sent to user when `max` is exceeded. May be a `string`, JSON object, or any other value + * that Express's `req.send()` supports. Defaults to `'Too many requests, please try again later.'`. + */ message?: string | Buffer | Message; - skip?(req: express.Request, res: express.Response): boolean; - skipFailedRequests?: boolean; - statusCode?: number; - store?: Store; + + /** + * Function that is called the first time `max` is exceeded. The `req.rateLimit` object has `limit`, `current`, + * and `remaining` number of requests and, if the store provides it, a `resetTime` Date object. Default is + * an empty function. + * Default: `(req, res, opts) => {}` + */ onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + + /** + * Function used to skip requests. Returning `true` from the function will skip limiting for that request. Defaults to + * always `false` (count all requests). + * Default: `(req, res) => false` + */ + skip?(req: express.Request, res: express.Response): boolean; + + /** + * When set to `true`, failed requests (status >= 400, request canceled or errored) won't be counted. Defaults to `false`. + */ + skipFailedRequests?: boolean; + + /** + * When set to `true`, successful requests (status < 400) won't be counted. Defaults to `false`. + */ + skipSuccessfulRequests?: boolean; + + /** + * HTTP status code returned when `max` is exceeded. Defaults to `429`. + */ + statusCode?: number; + + /** + * The storage to use when persisting rate limit attempts. + */ + store?: Store; + + /** + * How long in milliseconds to keep records of requests in memory. Defaults to `60000` (1 minute). + */ windowMs?: number; } } diff --git a/types/express-rate-limit/v2/express-rate-limit-tests.ts b/types/express-rate-limit/v2/express-rate-limit-tests.ts new file mode 100644 index 0000000000..aa5c51a016 --- /dev/null +++ b/types/express-rate-limit/v2/express-rate-limit-tests.ts @@ -0,0 +1,39 @@ +import RateLimit = require("express-rate-limit"); + +const apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +const apiLimiterWithMessageObject = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + message: { + status: 429, + message: 'To many requests, try again later' + } +}); + +const createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour", + handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`)) +}); + +const callbackWithFewerParams = new RateLimit({ + handler: (req, res) => res.status(429).json(`TooManyRequests: ${req.ip}`) +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + decrement(key: string) { } + resetKey(key: string) { } +} + +const limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/types/express-rate-limit/v2/index.d.ts b/types/express-rate-limit/v2/index.d.ts new file mode 100644 index 0000000000..b3f074f28d --- /dev/null +++ b/types/express-rate-limit/v2/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for express-rate-limit 2.9 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher , makepost +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + interface Store { + incr(key: string, cb: StoreIncrementCallback): void; + decrement(key: string): void; + resetKey(key: string): void; + } + + interface Message { + status: number; + message: string; + [key: string]: any; + } + + interface Options { + delayAfter?: number; + delayMs?: number; + handler?(req: express.Request, res: express.Response, next: express.NextFunction): any; + headers?: boolean; + keyGenerator?(req: express.Request, res: express.Response): string; + max?: number; + message?: string | Buffer | Message; + skip?(req: express.Request, res: express.Response): boolean; + skipFailedRequests?: boolean; + statusCode?: number; + store?: Store; + onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + windowMs?: number; + } +} + +declare var RateLimit: new (options: RateLimit.Options) => express.RequestHandler; +export = RateLimit; diff --git a/types/express-rate-limit/v2/tsconfig.json b/types/express-rate-limit/v2/tsconfig.json new file mode 100644 index 0000000000..0e9b4d2ad4 --- /dev/null +++ b/types/express-rate-limit/v2/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "express-rate-limit": ["express-rate-limit/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] +} diff --git a/types/express-rate-limit/v2/tslint.json b/types/express-rate-limit/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-rate-limit/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4cace8f646c6c7173dbd2370f95296c06c2e4e2c Mon Sep 17 00:00:00 2001 From: Taku Shimosawa Date: Wed, 2 Jan 2019 17:51:25 -0800 Subject: [PATCH 153/225] [bytebuffer] Change to/add Buffer in the types for arguments and return types --- types/bytebuffer/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index 4423d7872b..bafed6edf8 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -146,7 +146,7 @@ declare class ByteBuffer /** * Concatenates multiple ByteBuffers into one. */ - static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; + static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; /** * Decodes a base64 encoded string to a ByteBuffer. @@ -185,7 +185,7 @@ declare class ByteBuffer * @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN. * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT. */ - static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + static wrap( buffer: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; /** * Decodes a zigzag encoded signed 32bit integer. @@ -220,7 +220,7 @@ declare class ByteBuffer /** * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length. */ - append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; + append( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; /** * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data. @@ -291,7 +291,7 @@ declare class ByteBuffer /** * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. */ - prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer; + prepend( source: ByteBuffer | string | ArrayBuffer | Buffer, encoding?: string | number, offset?: number ): ByteBuffer; /** * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. @@ -480,7 +480,7 @@ declare class ByteBuffer /** * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. */ - toBuffer( forceCopy?: boolean ): ArrayBuffer; + toBuffer( forceCopy?: boolean ): Buffer; /** *Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: @@ -517,7 +517,7 @@ declare class ByteBuffer /** * Writes an array of bytes. This is an alias for append */ - writeBytes( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; + writeBytes( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; /** * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself. From e50421936ea216ae862fb88afe78a502900553da Mon Sep 17 00:00:00 2001 From: Wouter R Date: Thu, 3 Jan 2019 19:34:43 +0100 Subject: [PATCH 154/225] Remove tslint ban-types config override in favor of inline overrides. --- types/mongoose-paginate-v2/index.d.ts | 3 +++ types/mongoose-paginate-v2/tslint.json | 5 +---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/mongoose-paginate-v2/index.d.ts b/types/mongoose-paginate-v2/index.d.ts index dfd70cc0cb..ca8b7eac91 100644 --- a/types/mongoose-paginate-v2/index.d.ts +++ b/types/mongoose-paginate-v2/index.d.ts @@ -20,10 +20,13 @@ declare module 'mongoose' { } interface PaginateOptions { + /* tslint:disable-next-line: ban-types */ select?: Object | string; + /* tslint:disable-next-line: ban-types */ sort?: Object | string; customLabels?: CustomLabels; collation?: CollationOptions; + /* tslint:disable-next-line: ban-types */ populate?: Object[] | string[] | Object | string; lean?: boolean; leanWithId?: boolean; diff --git a/types/mongoose-paginate-v2/tslint.json b/types/mongoose-paginate-v2/tslint.json index a62d0d4e68..f93cf8562a 100644 --- a/types/mongoose-paginate-v2/tslint.json +++ b/types/mongoose-paginate-v2/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false - } + "extends": "dtslint/dt.json" } From 45f849476129c3f383ecc59742c3b9f19cbea55a Mon Sep 17 00:00:00 2001 From: Jeremy Forsythe Date: Thu, 3 Jan 2019 13:53:52 -0500 Subject: [PATCH 155/225] fix function call and handle augmented Request --- .../express-slow-down-tests.ts | 20 ++++++---- types/express-slow-down/index.d.ts | 38 ++++++++++++++++++- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/types/express-slow-down/express-slow-down-tests.ts b/types/express-slow-down/express-slow-down-tests.ts index 46ab215848..e7d049bd7d 100644 --- a/types/express-slow-down/express-slow-down-tests.ts +++ b/types/express-slow-down/express-slow-down-tests.ts @@ -1,8 +1,8 @@ -import SlowDown = require("express-slow-down"); +import slowDown = require("express-slow-down"); -const slowerAllDefaults = new SlowDown({}); +const slowerAllDefaults = slowDown({}); -const slowerWithOptions = new SlowDown({ +const slowerWithOptions = slowDown({ windowMs: 15 * 60 * 1000, // 15 minutes, delayAfter: 1, delayMs: 0, // disabled @@ -10,18 +10,22 @@ const slowerWithOptions = new SlowDown({ skipSuccessfulRequests: true, }); -const slowerWithCallbacks = new SlowDown({ +const slowerWithCallbacks = slowDown({ keyGenerator: (req, res) => req.ip, skip: (req, res) => false, - onLimitReached: (req, res, opts) => {}, + onLimitReached: (req, res, opts) => { + console.log(req.slowDown.current); + console.log(req.slowDown.remaining); + console.log(req.slowDown.limit); + }, }); -class MockStore implements SlowDown.Store { - incr(key: string, cb: SlowDown.StoreIncrementCallback) { } +class MockStore implements slowDown.Store { + incr(key: string, cb: slowDown.StoreIncrementCallback) { } decrement(key: string) { } resetKey(key: string) { } } -const slowerWithStore = new SlowDown({ +const slowerWithStore = slowDown({ store: new MockStore() }); diff --git a/types/express-slow-down/index.d.ts b/types/express-slow-down/index.d.ts index a446ca4f11..0ab76adb8f 100644 --- a/types/express-slow-down/index.d.ts +++ b/types/express-slow-down/index.d.ts @@ -9,6 +9,40 @@ import express = require("express"); declare namespace SlowDown { type StoreIncrementCallback = (err?: {}, hits?: number) => void; + interface SlowDownRequestAugmentation { + /** + * The `options.delayAfter` value + */ + limit: number; + + /** + * The number of requests in the current window + */ + current: number; + + /** + * the number of requests remaining before rate-limiting begins + */ + remaining: number; + + /** + * When the window will reset, `current` will return to `0`, and `remaining` will return + * to limit. Represents milliseconds since epoch (compare to `Date.now()`). This field + * depends on store support. It will be `undefined` if the store does not provide the value. + */ + resetTime?: number; + + /** + * Amount of delay imposed on current request in milliseconds + */ + delay: number; + } + + /** + * Express Request with the added `slowDown` property + */ + type RequestWithSlowDown = express.Request & { slowDown: SlowDownRequestAugmentation } + interface Store { incr(key: string, cb: StoreIncrementCallback): void; decrement(key: string): void; @@ -62,7 +96,7 @@ declare namespace SlowDown { * Function to execute the first time the limit is reached within `windowMs`. * Default: `(req, res, opts) => {}` */ - onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + onLimitReached?(req: RequestWithSlowDown, res: express.Response, optionsUsed: Options): void; /** * The storage to use when persisting request attempts. By default, the MemoryStore is used. @@ -71,5 +105,5 @@ declare namespace SlowDown { } } -declare var SlowDown: new (options: SlowDown.Options) => express.RequestHandler; +declare var SlowDown: (options: SlowDown.Options) => express.RequestHandler; export = SlowDown; From 59d63bd16121fe914f7e87e5a304fbc7b1e30597 Mon Sep 17 00:00:00 2001 From: Jeremy Forsythe Date: Thu, 3 Jan 2019 14:03:06 -0500 Subject: [PATCH 156/225] fix tests --- types/express-slow-down/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/types/express-slow-down/index.d.ts b/types/express-slow-down/index.d.ts index 0ab76adb8f..9e49f6ba64 100644 --- a/types/express-slow-down/index.d.ts +++ b/types/express-slow-down/index.d.ts @@ -41,7 +41,7 @@ declare namespace SlowDown { /** * Express Request with the added `slowDown` property */ - type RequestWithSlowDown = express.Request & { slowDown: SlowDownRequestAugmentation } + type RequestWithSlowDown = express.Request & { slowDown: SlowDownRequestAugmentation }; interface Store { incr(key: string, cb: StoreIncrementCallback): void; @@ -105,5 +105,4 @@ declare namespace SlowDown { } } -declare var SlowDown: (options: SlowDown.Options) => express.RequestHandler; -export = SlowDown; +export function SlowDown(options: SlowDown.Options): express.RequestHandler; From 6ca38e89115b17ce7b7b77bd64fe69bc1d18671c Mon Sep 17 00:00:00 2001 From: Jeremy Forsythe Date: Thu, 3 Jan 2019 14:26:39 -0500 Subject: [PATCH 157/225] fix lint and better interface definition --- types/express-slow-down/index.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/express-slow-down/index.d.ts b/types/express-slow-down/index.d.ts index 9e49f6ba64..f7aeab76fd 100644 --- a/types/express-slow-down/index.d.ts +++ b/types/express-slow-down/index.d.ts @@ -41,7 +41,9 @@ declare namespace SlowDown { /** * Express Request with the added `slowDown` property */ - type RequestWithSlowDown = express.Request & { slowDown: SlowDownRequestAugmentation }; + interface RequestWithSlowDown extends express.Request { + slowDown: SlowDownRequestAugmentation; + } interface Store { incr(key: string, cb: StoreIncrementCallback): void; @@ -105,4 +107,5 @@ declare namespace SlowDown { } } -export function SlowDown(options: SlowDown.Options): express.RequestHandler; +declare function SlowDown(options: SlowDown.Options): express.RequestHandler; +export = SlowDown; From 3d61a8f7b0b0477ea9b5b30da4f263b1782b46ec Mon Sep 17 00:00:00 2001 From: Akuukis Date: Fri, 4 Jan 2019 04:05:35 +0200 Subject: [PATCH 158/225] [stellar-sdk] Misc improvements 3 (#31857) * fix(operations): review props and options * feat(op): setOptions signer conditional type * fix: Server.ServerOptions -> Server.Options --- types/stellar-sdk/index.d.ts | 200 +++++++++++++------------ types/stellar-sdk/stellar-sdk-tests.ts | 12 ++ 2 files changed, 116 insertions(+), 96 deletions(-) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index 89f534c629..82ee2f583e 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stellar-sdk 0.10 +// Type definitions for stellar-sdk 0.11 // Project: https://github.com/stellar/js-stellar-sdk // Definitions by: Carl Foster // Triston Jones @@ -154,98 +154,89 @@ export namespace StellarBase { } namespace Operation { - interface Operation { - type: OperationType; - source: string | null; - } - interface AccountMerge extends Operation { - type: OperationType.accountMerge; - destination: string; - } - interface AccountMergeOptions { - destination: string; + interface Operation { + type: T; source?: string; } + interface OperationOptions { + source?: string; + } + + interface AccountMerge extends Operation { + destination: string; + } + interface AccountMergeOptions extends OperationOptions { + destination: string; + } function accountMerge(options: AccountMergeOptions): xdr.Operation; - interface AllowTrust extends Operation { - type: OperationType.allowTrust; + interface AllowTrust extends Operation { trustor: string; assetCode: string; - authorize: boolean; + authorize: boolean | undefined; } - interface AllowTrustOptions { + interface AllowTrustOptions extends OperationOptions { trustor: string; assetCode: string; - authorize: boolean; - source?: string; + authorize?: boolean; } function allowTrust(options: AllowTrustOptions): xdr.Operation; - interface ChangeTrust extends Operation { - type: OperationType.changeTrust; + interface ChangeTrust extends Operation { line: Asset; - limit: string | number; + limit: string; } - interface ChangeTrustOptions { + interface ChangeTrustOptions extends OperationOptions { asset: Asset; limit?: string; - source?: string; } function changeTrust(options: ChangeTrustOptions): xdr.Operation; - interface CreateAccount extends Operation { - type: OperationType.createAccount; - source: string; + interface CreateAccount extends Operation { destination: string; - startingBalance: string | number; + startingBalance: string; } - interface CreateAccountOptions { + interface CreateAccountOptions extends OperationOptions { destination: string; startingBalance: string; - source?: string; } function createAccount(options: CreateAccountOptions): xdr.Operation; - interface CreatePassiveOffer extends Operation { - type: OperationType.createPassiveOffer; - selling: Asset; - buying: Asset; - amount: string | number; - price: string | number; - } - interface CreatePassiveOfferOptions { + interface CreatePassiveOffer extends Operation { selling: Asset; buying: Asset; amount: string; - price: number | string | object; - source?: string; + price: string; + } + interface CreatePassiveOfferOptions extends OperationOptions { + selling: Asset; + buying: Asset; + amount: string; + price: number | string | object /* bignumber.js */; } function createPassiveOffer(options: CreatePassiveOfferOptions): xdr.Operation; - interface Inflation extends Operation { - type: OperationType.inflation; + interface Inflation extends Operation { } - function inflation(options: { source?: string }): xdr.Operation; + interface InflationOptions extends OperationOptions { // tslint:disable-line + } + function inflation(options: InflationOptions): xdr.Operation; - interface ManageData extends Operation { - type: OperationType.manageData; + interface ManageData extends Operation { name: string; value: Buffer; } - interface ManageDataOptions { + interface ManageDataOptions extends OperationOptions { name: string; value: string | Buffer; - source?: string; } function manageData(options: ManageDataOptions): xdr.Operation; - interface ManageOffer extends Operation { - type: OperationType.manageOffer; + interface ManageOffer extends Operation { selling: Asset; buying: Asset; - amount: string | number; - price: string | number; + amount: string; + price: string; offerId: string; } interface ManageOfferOptions extends CreatePassiveOfferOptions { @@ -253,37 +244,33 @@ export namespace StellarBase { } function manageOffer(options: ManageOfferOptions): xdr.Operation; - interface PathPayment extends Operation { - type: OperationType.pathPayment; - sendAsset: Asset; - sendMax: string | number; - destination: string; - destAsset: Asset; - destAmount: string | number; - path: Asset[]; - } - interface PathPaymentOptions { + interface PathPayment extends Operation { sendAsset: Asset; sendMax: string; destination: string; destAsset: Asset; destAmount: string; path: Asset[]; - source?: string; + } + interface PathPaymentOptions extends OperationOptions { + sendAsset: Asset; + sendMax: string; + destination: string; + destAsset: Asset; + destAmount: string; + path?: Asset[]; } function pathPayment(options: PathPaymentOptions): xdr.Operation; - interface Payment extends Operation { - type: OperationType.payment; - destination: string; - asset: Asset; - amount: string | number; - } - interface PaymentOptions { - destination: string; - asset: Asset; + interface Payment extends Operation { amount: string; - source?: string; + asset: Asset; + destination: string; + } + interface PaymentOptions extends OperationOptions { + amount: string; + asset: Asset; + destination: string; } function payment(options: PaymentOptions): xdr.Operation; @@ -297,14 +284,49 @@ export namespace StellarBase { Revocable = 2, Immutable = 4, } - interface Signer { - ed25519PublicKey?: string; - sha256Hash?: Buffer | string; - preAuthTx?: Buffer | string; + interface SignerEd25519PublicKey { + ed25519PublicKey: string; + weight: number | undefined; + } + interface SignerSha256Hash { + sha256Hash: Buffer; + weight: number | undefined; + } + interface SignerPreAuthTx { + preAuthTx: Buffer; + weight: number | undefined; + } + type Signer = SignerEd25519PublicKey | SignerSha256Hash | SignerPreAuthTx; + interface SignerEd25519PublicKeyOptions { + ed25519PublicKey: string; weight?: number | string; } - interface SetOptions extends Operation { - type: OperationType.setOptions; + interface SignerSha256HashOptions { + sha256Hash: Buffer | string; + weight?: number | string; + } + interface SignerPreAuthTxOptions { + preAuthTx: Buffer | string; + weight?: number | string; + } + type SignerOptions = SignerEd25519PublicKeyOptions | SignerSha256HashOptions | SignerPreAuthTxOptions; + type SignerUnion = {ed25519PublicKey: any} | {sha256Hash: any} | {preAuthTx: any} | null; + interface SetOptions extends Operation { + inflationDest?: string; + clearFlags?: AuthFlags; + setFlags?: AuthFlags; + masterWeight?: number; + lowThreshold?: number; + medThreshold?: number; + highThreshold?: number; + homeDomain?: string; + signer: + T extends {ed25519PublicKey: any} ? SignerEd25519PublicKey : + T extends {sha256Hash: any} ? SignerSha256Hash : + T extends {preAuthTx: any} ? SignerPreAuthTx : + never; + } + interface SetOptionsOptions extends OperationOptions { inflationDest?: string; clearFlags?: AuthFlags; setFlags?: AuthFlags; @@ -313,29 +335,15 @@ export namespace StellarBase { medThreshold?: number | string; highThreshold?: number | string; homeDomain?: string; - signer?: Signer; + signer?: T; } - interface SetOptionsOptions { - inflationDest?: string; - clearFlags?: AuthFlags; - setFlags?: AuthFlags; - masterWeight?: number | string; - lowThreshold?: number | string; - medThreshold?: number | string; - highThreshold?: number | string; - signer?: Signer; - homeDomain?: string; - source?: string; - } - function setOptions(options: SetOptionsOptions): xdr.Operation; + function setOptions(options: SetOptionsOptions): xdr.Operation>; - interface BumpSequence extends Operation { - type: OperationType.bumpSequence; + interface BumpSequence extends Operation { bumpTo: string; } - interface BumpSequenceOptions { + interface BumpSequenceOptions extends OperationOptions { bumpTo: string; - source?: string; } function bumpSequence(options: BumpSequenceOptions): xdr.Operation; @@ -473,7 +481,7 @@ export namespace Config { } export class Server { - constructor(serverURL: string, options?: Server.ServerOptions) + constructor(serverURL: string, options?: Server.Options) accounts(): Server.AccountCallBuilder; assets(): Server.AssetsCallBuilder; effects(): Server.EffectCallBuilder; @@ -967,7 +975,7 @@ export namespace Server { forTransaction(transactionId: string): this; } - interface ServerOptions { + interface Options { allowHttp: boolean; } diff --git a/types/stellar-sdk/stellar-sdk-tests.ts b/types/stellar-sdk/stellar-sdk-tests.ts index bf991b4591..c4dcbda7c8 100644 --- a/types/stellar-sdk/stellar-sdk-tests.ts +++ b/types/stellar-sdk/stellar-sdk-tests.ts @@ -30,3 +30,15 @@ StellarSdk.Memo.hash('asdf').value; // $ExpectType Buffer // P.S. don't use Memo constructor (new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf')).value; // $ExpectType AnyValue (new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf')).type; // $ExpectType AnyType + +const noSignerXDR = StellarSdk.Operation.setOptions({lowThreshold: 1}); +StellarSdk.Operation.fromXDRObject(noSignerXDR).signer; // $ExpectType never + +const newSignerXDR1 = StellarSdk.Operation.setOptions({signer: {ed25519PublicKey: sourceKey.publicKey(), weight: '1'}}); +StellarSdk.Operation.fromXDRObject(newSignerXDR1).signer; // $ExpectType SignerEd25519PublicKey + +const newSignerXDR2 = StellarSdk.Operation.setOptions({signer: {sha256Hash: Buffer.from(''), weight: '1'}}); +StellarSdk.Operation.fromXDRObject(newSignerXDR2).signer; // $ExpectType SignerSha256Hash + +const newSignerXDR3 = StellarSdk.Operation.setOptions({signer: {preAuthTx: '', weight: 1}}); +StellarSdk.Operation.fromXDRObject(newSignerXDR3).signer; // $ExpectType SignerPreAuthTx From 34b631c6783abf448473a078b73e91feca87595e Mon Sep 17 00:00:00 2001 From: Taeheon Kim Date: Fri, 4 Jan 2019 11:06:38 +0900 Subject: [PATCH 159/225] Add "onBeforeDragStart" to the "DragDropContextProps" interface (#31865) --- types/react-beautiful-dnd/index.d.ts | 2 ++ types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index dfe6f21229..f917fc1a2d 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -5,6 +5,7 @@ // Austin Turner // Mark Nelissen // Enrico Boccadifuoco +// Taeheon Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -85,6 +86,7 @@ export interface DropResult extends DragUpdate { } export interface DragDropContextProps { + onBeforeDragStart?(initial: DragStart): void; onDragStart?(initial: DragStart, provided: ResponderProvided): void; onDragUpdate?(initial: DragUpdate, provided: ResponderProvided): void; onDragEnd(result: DropResult, provided: ResponderProvided): void; diff --git a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx index 93b7903818..ceb6757992 100644 --- a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx +++ b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx @@ -48,6 +48,10 @@ class App extends React.Component<{}, AppState> { this.onDragEnd = this.onDragEnd.bind(this); } + onBeforeDragStart(dragStart: DragStart) { + // + } + onDragStart(dragStart: DragStart, provided: ResponderProvided) { // } @@ -80,7 +84,7 @@ class App extends React.Component<{}, AppState> { render() { return ( - + {(provided, snapshot) => (
From 8d21ac9216f47c1a4739b5deb4df266a98fa2160 Mon Sep 17 00:00:00 2001 From: davidgoli Date: Thu, 3 Jan 2019 18:09:14 -0800 Subject: [PATCH 160/225] add extra parse signature --- types/url-parse/index.d.ts | 6 +++++- types/url-parse/url-parse-tests.ts | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index 58a14f3f4d..4d33354e9e 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for url-parse 1.4 // Project: https://github.com/unshiftio/url-parse -// Definitions by: Pavlo Chernenko , Hari Sivaramakrishnan , Dmitry Dushkin +// Definitions by: Pavlo Chernenko +// Hari Sivaramakrishnan +// Dmitry Dushkin +// David Golightly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -43,6 +46,7 @@ interface URLParse { declare const URLParse: { new(address: string, location?: string | object, parser?: boolean | URLParse.QueryParser): URLParse; (address: string, location?: string | object, parser?: boolean | URLParse.QueryParser): URLParse; + (address: string, parser?: boolean | URLParse.QueryParser): URLParse; extractProtocol(url: string): { slashes: boolean; diff --git a/types/url-parse/url-parse-tests.ts b/types/url-parse/url-parse-tests.ts index 87904b7f13..be8b8afe8c 100644 --- a/types/url-parse/url-parse-tests.ts +++ b/types/url-parse/url-parse-tests.ts @@ -5,6 +5,10 @@ new URL('foo/bar', 'https://github.com/'); new URL('foo/bar', 'https://github.com/', (query: string) => ({ query })); parse('foo/bar', 'https://github.com/'); parse('foo/bar', 'https://github.com/', (query: string) => ({ query })); +const result = parse('foo/bar?baz=quux', true); +if (result.query.baz !== 'quux') { + throw new Error('bad query parsing'); +} const url1: URL = new URL('https://github.com/foo/bar?baz=true'); url1.hash; From 305151cf2d4fdd0ce1ba36b4e0cd4e5ef381dddf Mon Sep 17 00:00:00 2001 From: paibamboo Date: Fri, 4 Jan 2019 10:22:41 +0700 Subject: [PATCH 161/225] Add onAfterClose prop to ReactModal --- types/react-modal/index.d.ts | 5 ++++- types/react-modal/react-modal-tests.tsx | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/types/react-modal/index.d.ts b/types/react-modal/index.d.ts index d04a6b5c18..2daa2a1a6f 100644 --- a/types/react-modal/index.d.ts +++ b/types/react-modal/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-modal 3.6 +// Type definitions for react-modal 3.8.1 // Project: https://github.com/reactjs/react-modal // Definitions by: Rajab Shakirov , // Drew Noakes , @@ -64,6 +64,9 @@ declare namespace ReactModal { /* Function that will be run after the modal has opened. */ onAfterOpen?(): void; + /* Function that will be run after the modal has closed. */ + onAfterClose?(): void; + /* Function that will be run when the modal is requested to be closed, prior to actually closing. */ onRequestClose?(event: (MouseEvent | KeyboardEvent)): void; diff --git a/types/react-modal/react-modal-tests.tsx b/types/react-modal/react-modal-tests.tsx index 8dfd6d35e3..96c18ea881 100644 --- a/types/react-modal/react-modal-tests.tsx +++ b/types/react-modal/react-modal-tests.tsx @@ -12,6 +12,7 @@ class ExampleOfUsingReactModal extends React.Component { overlayRef: HTMLDivElement; render() { const onAfterOpenFn = () => { }; + const onAfterCloseFn = () => { }; const onRequestCloseFn = () => { }; const customStyle = { overlay: { @@ -59,6 +60,7 @@ class ExampleOfUsingReactModal extends React.Component { Date: Fri, 4 Jan 2019 14:09:05 +0800 Subject: [PATCH 162/225] [opentype.js] add annotations for BoundingBox and some tests, finish prev todo --- types/opentype.js/index.d.ts | 15 +++++++++++++-- types/opentype.js/opentype.js-tests.ts | 2 ++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/opentype.js/index.d.ts b/types/opentype.js/index.d.ts index 8dc449784d..5fdc257362 100644 --- a/types/opentype.js/index.d.ts +++ b/types/opentype.js/index.d.ts @@ -367,8 +367,19 @@ export interface PathCommand { * UTIL CLASSES ******************************************/ -export type BoundingBox = () => any; -// TODO add methods +export class BoundingBox { + x1: number; + y1: number; + x2: number; + y2: number; + + isEmpty(): boolean; + addPoint(x: number, y: number): void; + addX(x: number): void; + addY(y: number): void; + addBezier(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; + addQuad(x0: number, y0: number, x1: number, y1: number, x: number, y: number): void; +} export interface Encoding { charset: string; diff --git a/types/opentype.js/opentype.js-tests.ts b/types/opentype.js/opentype.js-tests.ts index 04781d5415..e3695944db 100644 --- a/types/opentype.js/opentype.js-tests.ts +++ b/types/opentype.js/opentype.js-tests.ts @@ -113,6 +113,8 @@ aPath.extend(aPath); aPath.extend(aPath.commands); aPath.extend(aPath.getBoundingBox()); const pathBBox: opentype.BoundingBox = aPath.getBoundingBox(); +pathBBox.addQuad(1, 1, 1, 1, 1, 1); +const yDist = pathBBox.y2 - pathBBox.y1; aPath.draw(ctx); const pathData: string = aPath.toPathData(7); const pathSvg: string = aPath.toSVG(7); From f4417875ccd9964b8e64822b7dd8c582353178b8 Mon Sep 17 00:00:00 2001 From: paibamboo Date: Fri, 4 Jan 2019 13:26:08 +0700 Subject: [PATCH 163/225] Fix build error patch version not allowed --- types/react-modal/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-modal/index.d.ts b/types/react-modal/index.d.ts index 2daa2a1a6f..0117a69656 100644 --- a/types/react-modal/index.d.ts +++ b/types/react-modal/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-modal 3.8.1 +// Type definitions for react-modal 3.8 // Project: https://github.com/reactjs/react-modal // Definitions by: Rajab Shakirov , // Drew Noakes , From c8aebb07540f5b9e66a5d80707594c6750e4fc65 Mon Sep 17 00:00:00 2001 From: Vince Varga Date: Thu, 3 Jan 2019 16:27:01 +0100 Subject: [PATCH 164/225] Add navigator.permissions API type definitions --- types/navigator-permissions/index.d.ts | 180 ++++++++++++++++++ .../navigator-permissions-tests.ts | 45 +++++ types/navigator-permissions/tsconfig.json | 24 +++ types/navigator-permissions/tslint.json | 1 + 4 files changed, 250 insertions(+) create mode 100644 types/navigator-permissions/index.d.ts create mode 100644 types/navigator-permissions/navigator-permissions-tests.ts create mode 100644 types/navigator-permissions/tsconfig.json create mode 100644 types/navigator-permissions/tslint.json diff --git a/types/navigator-permissions/index.d.ts b/types/navigator-permissions/index.d.ts new file mode 100644 index 0000000000..a62c7f77ef --- /dev/null +++ b/types/navigator-permissions/index.d.ts @@ -0,0 +1,180 @@ +// Type definitions for Navigator.Permissions 0.1 +// Project: https://developer.mozilla.org/en-US/docs/Web/API/Permissions +// Definitions by: Vince Varga , MindDoc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** + * Namespace for `navigator.permissions` type definitions. + * + * As the Permissions API is only supported by Firefox and Chrome + * https://caniuse.com/#feat=permissions-api + * the TypeScript team has not yet added it to lib.dom.d.ts + * https://github.com/Microsoft/TypeScript/issues/24923 + * In the meantime, these type definitions can be used. + * + * The documentation is based on the MDN web docs + * https://developer.mozilla.org/en-US/docs/Web/API/Permissions + */ +declare namespace NavigatorPermissions { + /** + * Permission state values. + */ + type PermissionState = + 'granted' | + 'denied' | + 'prompt'; + + /** + * The `PermissionStatus` interface of the Permissions API provides the state + * of an object and an event handler for monitoring changes to said state. + * + * This is an experimental technology + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PermissionStatus} + */ + interface PermissionStatus extends EventTarget { + /** + * Returns the state of a requested permission. + */ + readonly state: PermissionState; + /** + * Returns the state of a requested permission. + * Later versions of the specification replace this with + * `PermissionStatus.state`. + * @deprecated + */ + readonly status: PermissionState; + /** + * An event called whenever `PermissionStatus.status` changes. + */ + onchange: ((this: this, event: Event) => any) | null; + } + + /** + * Permission name options. + */ + type PermissionName = + 'accelerometer' | + 'accessibility-events' | + 'ambient-light-sensor' | + 'background-sync' | + 'camera' | + 'clipboard-read' | + 'clipboard-write' | + 'geolocation' | + 'gyroscope' | + 'magnetometer' | + 'microphone' | + 'midi' | + 'notifications' | + 'payment-handler' | + 'persistent-storage' | + 'push'; + + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query} + */ + interface PermissionDescriptor { + /** + * The name of the API whose permissions you want to query. + * + * Please, be aware, that not all of these are supported in every browser + * that supports the Permissions API. For example, in Firefox you can't query + * the `'microphone'` or `'camera'` and it'll throw `TypeError` + */ + name: N; + } + + interface PushPermissionDescriptor extends PermissionDescriptor<'push'> { + /** + * Indicates whether you want to show a notification for every message + * or be able to send silent push + * notifications. The default is `false`. Not supported in Firefox. + */ + userVisibleOnly?: boolean; + } + + interface MidiPermissionDescriptor extends PermissionDescriptor<'midi'> { + /** + * Indicates whether you need and/or receive system exclusive + * messages. The default is false. + */ + sysex?: boolean; + } + + // Map permission names to correctly typed descriptors. + interface NameDescriptorMap { + // ??? Question ???: + // Is there a better way to handle this case and remove repeated code, + // something like + // > { + // [n in N]: D; // this line to cover all basic cases + // // and the custom permission descriptors for midi and push + // } + 'accelerometer': PermissionDescriptor<'accelerometer'>; + 'accessibility-events': PermissionDescriptor<'accessibility-events'>; + 'ambient-light-sensor': PermissionDescriptor<'ambient-light-sensor'>; + 'background-sync': PermissionDescriptor<'background-sync'>; + 'camera': PermissionDescriptor<'camera'>; + 'clipboard-read': PermissionDescriptor<'clipboard-read'>; + 'clipboard-write': PermissionDescriptor<'clipboard-write'>; + 'geolocation': PermissionDescriptor<'geolocation'>; + 'gyroscope': PermissionDescriptor<'gyroscope'>; + 'magnetometer': PermissionDescriptor<'magnetometer'>; + 'microphone': PermissionDescriptor<'microphone'>; + 'notifications': PermissionDescriptor<'notifications'>; + 'payment-handler': PermissionDescriptor<'payment-handler'>; + 'persistent-storage': PermissionDescriptor<'persistent-storage'>; + // These permission descriptors support extra properties + 'midi': MidiPermissionDescriptor; + 'push': PushPermissionDescriptor; + } + + /** + * The `Permissions` interface of the Permissions API provides the core + * Permission API functionality, such as methods for querying and + * revoking permissions. + * + * This is an experimental technology. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions} + */ + interface Permissions { + /** + * The `Permissions.query()` method of the `Permissions` interface returns + * the state of a user permission on the global scope. + * @param permissionDescriptor object that sets + * options for the query operation consisting of a comma-separated list + * of name-value pairs. + * (Is comma-separated list really supported? It is mentioned in the docs, but does not work). + * @returns the user permission status for a given API. + * @throws `TypeError` Retrieving the `PermissionDescriptor` information + * failed in some way, or the permission doesn't exist or is currently + * unsupported (e.g. `midi`, or `push` with `userVisibleOnly`). + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query} + */ + query(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise; + /** + * The `Permissions.revoke()` method of the `Permissions` interface reverts a + * currently set permission back to its default state, which is usually `prompt`. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Permissions/revoke} + */ + revoke(permissionDescriptor: NameDescriptorMap[keyof NameDescriptorMap]): Promise; + } + + /** + * Navigator type definition with possible `permissions` API support. + * + * This interface adds the `permissions` property to the navigator. + */ + interface NavigatorPermissions extends Navigator { + /** + * Provides the core Permission API functionality, such as querying and revoking permissions. + * + * The typing takes into account that the feature is not widely supported, + * making code using this API more secure by forcing considering the `undefined` case. + */ + permissions?: Permissions; + } +} diff --git a/types/navigator-permissions/navigator-permissions-tests.ts b/types/navigator-permissions/navigator-permissions-tests.ts new file mode 100644 index 0000000000..918726b23d --- /dev/null +++ b/types/navigator-permissions/navigator-permissions-tests.ts @@ -0,0 +1,45 @@ +// Here are some examples for Navigator.Permissions types. +// Open it in your IDE with TypeScript support and observe the types and documentation help +// that this module provides + +// Navigator from lib.dom might have permissions +const nav = navigator as NavigatorPermissions.NavigatorPermissions; + +async function exampleQueryAndEventListeners() { + // Force users to check for undefined as the feature is not widely supported + if (typeof nav.permissions === 'undefined') { return; } + const permissionsStatus = await nav.permissions.query({ name: 'camera' }); + // Possible state values are known to users: + const isDenied = permissionsStatus.state === 'denied'; + // if compared to any non-valid value, it warns + // const tsShouldWarn = permissionsStatus.state === 'can you see the warning?'; + permissionsStatus.addEventListener('change', (event) => { + console.log('permission state changed'); + // I couldn't find a way to set the EventTarget's type to PermissionStatus + console.log('new PermissionStatus', event.target); + }); +} + +function exampleQueryOptions() { + // Force users to check for undefined as the feature is not widely supported + if (typeof nav.permissions === 'undefined') { return; } + // query method checks if the name is a valid permission name + nav.permissions.query({ name: 'camera' }); + // Other names would cause type errors + // nav.permissions.query({ name: 'invalid name' }); + + // When permission name is 'push', userVisibleOnly property is also supported + nav.permissions.query({ name: 'push', userVisibleOnly: true }); + // For other names, it would fail: + // nav.permissions.query({ name: 'camera', userVisibleOnly: true }); + + // When permission name is 'midi', sysex property is also supported + nav.permissions.query({ name: 'midi', sysex: true }); + // For other names, it would fail: + // nav.permissions.query({ name: 'camera', sysex: true }); +} + +function exampleIgnoreUndefinedCheck() { + // Using the ! after permissions will let you bypass the undefined-check + nav.permissions!.query({ name: 'microphone' }); +} diff --git a/types/navigator-permissions/tsconfig.json b/types/navigator-permissions/tsconfig.json new file mode 100644 index 0000000000..c072886b33 --- /dev/null +++ b/types/navigator-permissions/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", + "navigator-permissions-tests.ts" + ] +} diff --git a/types/navigator-permissions/tslint.json b/types/navigator-permissions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/navigator-permissions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5950b10aed88f4fc785a6e92158603f4d6713e41 Mon Sep 17 00:00:00 2001 From: Guillaume Mayer Date: Fri, 4 Jan 2019 11:48:30 -0300 Subject: [PATCH 165/225] failing test (sort of) --- types/koa-router/koa-router-tests.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 51e95fb8a5..50e66509ea 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -49,6 +49,10 @@ const match = router.match('/users/:id', 'GET'); let layer: Router.Layer let layerOptions: Router.ILayerOptions +const mw: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { + ctx.body = "Ok"; +}; + app.use(router.routes()); app.use(router.allowedMethods()); From 6e13e6088f3eab8874141412f27d23a6c6d4975a Mon Sep 17 00:00:00 2001 From: Guillaume Mayer Date: Fri, 4 Jan 2019 11:49:20 -0300 Subject: [PATCH 166/225] fix --- types/koa-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 81b0f697e6..b2163d09d1 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -43,7 +43,7 @@ declare namespace Router { strict?: boolean; } - export interface IRouterContext { + export interface IRouterContext extends Koa.Context { /** * url params */ From 8085094f30ad662b8226355079c3f75f4388ef3d Mon Sep 17 00:00:00 2001 From: Daniel Schopf Date: Fri, 4 Jan 2019 17:27:19 +0100 Subject: [PATCH 167/225] Add terser-webpack-plugin (#31863) * Added terser plugin typings * add webpack chunk typing * added 'ExtractCommentOptions' instead of just 'object' --- types/terser-webpack-plugin/index.d.ts | 54 +++++++++++++++++++ .../terser-webpack-plugin-tests.ts | 36 +++++++++++++ types/terser-webpack-plugin/tsconfig.json | 23 ++++++++ types/terser-webpack-plugin/tslint.json | 1 + 4 files changed, 114 insertions(+) create mode 100644 types/terser-webpack-plugin/index.d.ts create mode 100644 types/terser-webpack-plugin/terser-webpack-plugin-tests.ts create mode 100644 types/terser-webpack-plugin/tsconfig.json create mode 100644 types/terser-webpack-plugin/tslint.json diff --git a/types/terser-webpack-plugin/index.d.ts b/types/terser-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..5d1afa1a52 --- /dev/null +++ b/types/terser-webpack-plugin/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for terser-webpack-plugin 1.2 +// Project: https://github.com/webpack-contrib/terser-webpack-plugin +// Definitions by: Daniel Schopf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import { Plugin } from 'webpack'; +import { MinifyOptions } from 'terser'; +import webpack = require('webpack'); + +export = TerserPlugin; + +declare class TerserPlugin extends Plugin { + constructor(opts?: TerserPlugin.TerserPluginOptions); +} + +declare namespace TerserPlugin { + interface MinifyResult { + error: any; + map: any; + code: any; + warnings: any; + extractedComments: any; + } + + interface ExtractCommentOptions { + condition: boolean | string | RegExp | ExtractCommentFn | object; + filename?: string | FormatFn; + banner?: boolean | string | FormatFn; + } + + type ExtractCommentFn = (node: any, comment: any) => (boolean | object); + + type FormatFn = (input: string) => string; + + interface TerserPluginOptions { + test?: string | RegExp | Array; + include?: string | RegExp | Array; + exclude?: string | RegExp | Array; + chunkFilter?: (chunk: webpack.compilation.Chunk) => boolean; + cache?: boolean | string; + cacheKeys?: (defaultCacheKeys: any, file: any) => object; + parallel?: boolean | number; + sourceMap?: boolean; + minify?: (file: any, sourceMap: any) => MinifyResult; + terserOptions?: MinifyOptions; + extractComments?: boolean + | string + | RegExp + | ExtractCommentFn + | ExtractCommentOptions; + warningsFilter?: (warning: any, source: any) => boolean; + } +} diff --git a/types/terser-webpack-plugin/terser-webpack-plugin-tests.ts b/types/terser-webpack-plugin/terser-webpack-plugin-tests.ts new file mode 100644 index 0000000000..5b0540a4ff --- /dev/null +++ b/types/terser-webpack-plugin/terser-webpack-plugin-tests.ts @@ -0,0 +1,36 @@ +import * as webpack from 'webpack'; +import * as TerserPlugin from "terser-webpack-plugin"; + +const compiler = webpack({ + plugins: [ + new TerserPlugin(), + ], +}); + +const compilerOptions = webpack({ + plugins: [ + new TerserPlugin({ + // Uncomment lines below for cache invalidation correctly + cache: true, + cacheKeys: (defaultCacheKeys) => { + delete defaultCacheKeys.terser; + + return { + ...defaultCacheKeys, + 'uglify-js': require('uglify-js/package.json').version, + }; + }, + minify: (file, sourceMap) => { + // https://github.com/mishoo/UglifyJS2#minify-options + const uglifyJsOptions = { + /* your `uglify-js` package options */ + }; + return require('uglify-js').minify(file, uglifyJsOptions); + }, + include: /src\//, + exclude: /node_modules\//, + sourceMap: true, + terserOptions: { mangle: true } + }), + ], +}); diff --git a/types/terser-webpack-plugin/tsconfig.json b/types/terser-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..02669a9daa --- /dev/null +++ b/types/terser-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", + "terser-webpack-plugin-tests.ts" + ] +} diff --git a/types/terser-webpack-plugin/tslint.json b/types/terser-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/terser-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 8a18392af3b5dd555cb920168668d15d11485e24 Mon Sep 17 00:00:00 2001 From: Nathan Fast Date: Fri, 4 Jan 2019 10:44:06 -0600 Subject: [PATCH 168/225] Add ignorePunctuation parameter to MarkOptions (#31873) --- types/mark.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/mark.js/index.d.ts b/types/mark.js/index.d.ts index 7b410ad65e..8b214c3e15 100644 --- a/types/mark.js/index.d.ts +++ b/types/mark.js/index.d.ts @@ -24,6 +24,7 @@ declare namespace Mark { acrossElements?: boolean; caseSensitive?: boolean; ignoreJoiners?: boolean; + ignorePunctuation?: string[]; wildcards?: 'disabled' | 'enabled' | 'withSpaces'; each?(element: Element): void; From 62b167feca55ad8b5c865f76c6bc63d7eb5a0b85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=95=E4=B9=90?= Date: Sat, 5 Jan 2019 00:44:52 +0800 Subject: [PATCH 169/225] Update ACLType in index.d.ts@types/ali-oss (#31819) * Update ACLType in index.d.ts ### From ```ts type ACLType = "public-read-write" | "public-read" | "and private"; ``` ### Tto ```ts type ACLType = "public-read-write" | "public-read" | "private"; ``` * Update index.d.ts * Update index.d.ts * Update index.d.ts --- types/ali-oss/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 13f7f56ff9..e4f9e09e7c 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -18,6 +18,7 @@ declare namespace OSS { internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. timeout?: string | number; // instance level timeout for all operations, default is 60s + cname?: boolean; // use custom domain name } interface Bucket { @@ -29,7 +30,7 @@ declare namespace OSS { type StorageType = "Standard" | "IA" | "Archive"; - type ACLType = "public-read-write" | "public-read" | "and private"; + type ACLType = "public-read-write" | "public-read" | "private"; type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; @@ -174,6 +175,7 @@ declare namespace OSS { mime?: string; // custom mime, will send with Content-Type entity header meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } callback: ObjectCallback; + headers?: object; } interface PutObjectResult { @@ -188,6 +190,7 @@ declare namespace OSS { mime: string; // custom mime, will send with Content-Type entity header meta: UserMeta; callback: ObjectCallback; + headers?: object; } interface AppendObjectOptions { From 0a779e312e545de2ab989d7eec72def644719a7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20Kadi=C5=A1a?= <8273932+martynaskadisa@users.noreply.github.com> Date: Fri, 4 Jan 2019 19:43:36 +0200 Subject: [PATCH 170/225] add typings for @loadable/component --- types/loadable__component/index.d.ts | 47 +++++++ .../loadable__component-tests.tsx | 117 ++++++++++++++++++ types/loadable__component/tsconfig.json | 29 +++++ types/loadable__component/tslint.json | 1 + 4 files changed, 194 insertions(+) create mode 100644 types/loadable__component/index.d.ts create mode 100644 types/loadable__component/loadable__component-tests.tsx create mode 100644 types/loadable__component/tsconfig.json create mode 100644 types/loadable__component/tslint.json diff --git a/types/loadable__component/index.d.ts b/types/loadable__component/index.d.ts new file mode 100644 index 0000000000..c4877bd8a9 --- /dev/null +++ b/types/loadable__component/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for @loadable/component 5.2 +// Project: https://github.com/smooth-code/loadable-components +// Definitions by: Martynas Kadiša +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface DefaultImportedComponent

{ + default: React.ComponentType

; +} + +export type DefaultComponent

= React.ComponentType

| DefaultImportedComponent

; + +export interface Options { + fallback?: JSX.Element; +} + +export type LoadableComponent = React.ComponentType; +export type LoadableLibrary = React.ComponentType<{ + fallback?: JSX.Element; + children?: (module: TModule) => React.ReactNode; + ref?: React.Ref; +}> & + TModule; + +declare function lib( + loadFn: (props: object) => Promise, + options?: Options +): LoadableLibrary; + +declare function loadableFunc( + loadFn: (props: T) => Promise>, + options?: Options +): LoadableComponent; + +declare const loadable: typeof loadableFunc & { lib: typeof lib }; + +export default loadable; + +export namespace lazy { + function lib(loadFn: (props: object) => Promise): LoadableLibrary; +} + +export function lazy(loadFn: (props: T) => Promise>): LoadableComponent; + +export function loadableReady(done?: () => any): Promise; diff --git a/types/loadable__component/loadable__component-tests.tsx b/types/loadable__component/loadable__component-tests.tsx new file mode 100644 index 0000000000..d286711be1 --- /dev/null +++ b/types/loadable__component/loadable__component-tests.tsx @@ -0,0 +1,117 @@ +import * as React from 'react'; +import loadable, { lazy, loadableReady } from '@loadable/component'; + +const TestComponent: React.SFC<{ foo: string }> = () => <>test; + +function defaultImportComponentLoader() { + return new Promise<{ default: typeof TestComponent }>(resolve => resolve({ default: TestComponent })); +} + +function importComponentLoader() { + return new Promise(resolve => resolve(TestComponent)); +} + +const lib = { + getTestObj: () => ({ bar: 'bar', foo: 'foo' }) +}; + +function defaultImportLibLoader() { + return new Promise<{ default: typeof lib }>(resolve => resolve(({ default: lib }))); +} + +function importLibLoader() { + return new Promise(resolve => resolve(lib)); +} + +// loadable +{ + // Should infer props from imported component with default export + const LoadableDefaultComponent = loadable(defaultImportComponentLoader); + ; + + // Should infer props from imported component without default export + const LoadableComponent = loadable(importComponentLoader); + ; + + // Should allow passing JSX element to fallback in options + loadable(defaultImportComponentLoader, { fallback:

loading...
}); + + // Should allow passing `fallback` prop to loadable component + loading...
} />; +} + +// lazy +{ + // Should infer props from imported component with default export + const LazyDefaultComponent = lazy(defaultImportComponentLoader); + ; + + // Should infer props from imported component without default export + const LazyComponent = lazy(importComponentLoader); + ; + + // Should allow passing fallback prop + loading...} />; +} + +// loadable.lib +{ + // Should infer types from module with default export and reflect them in children render prop + const LoadableDefaultLibrary = loadable.lib(defaultImportLibLoader); + + {({ default: { getTestObj } }) => getTestObj().foo} + ; + + // Should infer types from module without default export and reflect them in children render prop + const LoadableLibrary = loadable.lib(importLibLoader); + + {({ getTestObj }) => getTestObj().foo} + ; + + // Should allow passing fallback JSX element + loadable.lib(importLibLoader, { fallback:
loading lib...
}); + + // Should allow passing fallback prop + Loading library...}> + {({ getTestObj }) => getTestObj().foo} + ; + + // Should reflect inferred types from module in ref + const ref = React.createRef(); + ; + ref.current!.getTestObj().foo; +} + +// lazy.lib +{ + // Should infer types from module with default export and reflect them in children render prop + const LazyDefaultLibrary = lazy.lib(defaultImportLibLoader); + + {({ default: { getTestObj } }) => getTestObj().foo} + ; + + // Should infer types from module without default export and reflect them in children render prop + const LazyLibrary = lazy.lib(importLibLoader); + + {({ getTestObj }) => getTestObj().foo} + ; + + // Should allow passing fallback prop + Loading library...}> + {({ getTestObj }) => getTestObj().foo} + ; + + // Should reflect inferred types from module in ref + const ref = React.createRef(); + ; + ref.current!.getTestObj().foo; +} + +// loadableReady +{ + // Should allow passing callback argument + loadableReady(() => {}); + + // Should return a promise + loadableReady().then(() => {}); +} diff --git a/types/loadable__component/tsconfig.json b/types/loadable__component/tsconfig.json new file mode 100644 index 0000000000..440535e42b --- /dev/null +++ b/types/loadable__component/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@loadable/component": [ + "loadable__component" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "loadable__component-tests.tsx" + ] +} diff --git a/types/loadable__component/tslint.json b/types/loadable__component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/loadable__component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 742f59c19a984a3bbae16cb81e6f67113d99e635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20Kadi=C5=A1a?= <8273932+martynaskadisa@users.noreply.github.com> Date: Fri, 4 Jan 2019 19:54:16 +0200 Subject: [PATCH 171/225] add typings for @loadable/server --- types/loadable__server/index.d.ts | 86 +++++++++++++++++++ .../loadable__server-tests.tsx | 74 ++++++++++++++++ types/loadable__server/tsconfig.json | 29 +++++++ types/loadable__server/tslint.json | 1 + 4 files changed, 190 insertions(+) create mode 100644 types/loadable__server/index.d.ts create mode 100644 types/loadable__server/loadable__server-tests.tsx create mode 100644 types/loadable__server/tsconfig.json create mode 100644 types/loadable__server/tslint.json diff --git a/types/loadable__server/index.d.ts b/types/loadable__server/index.d.ts new file mode 100644 index 0000000000..eafbd7eec7 --- /dev/null +++ b/types/loadable__server/index.d.ts @@ -0,0 +1,86 @@ +// Type definitions for @loadable/server 5.2 +// Project: https://github.com/smooth-code/loadable-components +// Definitions by: Martynas Kadiša +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { ComponentType, ReactElement, Component } from 'react'; + +export type ChunkExtractorOptions = { + /** + * Webpack entrypoints to load (default to `["main"]`) + */ + entrypoints?: string | string[]; + /** + * Optional output path (only for `requireEntrypoint`) + */ + outputPath?: string; +} & ({ + /** + * Stats file path generated using `@loadable/webpack-plugin` + */ + statsFile: string; + } | { + /** + * Stats generated using `@loadable/webpack-plugin`. + */ + stats: object; + }); + +/** + * Used to collect chunks server-side and get them as script tags or script elements + */ +export class ChunkExtractor { + constructor(options: ChunkExtractorOptions); + + /** + * Wrap your application in a `ChunkExtractorManager` + */ + collectChunks( + /** + * JSX element that will be wrapped in `ChunkExtractorManager` + */ + element: JSX.Element + ): JSX.Element; + + /** + * Require the entrypoint of your application as a commonjs module. + */ + requireEntrypoint(name?: string): { default: ComponentType }; + + /** + * Get scripts as a string of `