From 5380cf2a252452830789e2951fe2ee4ef791d5d1 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Wed, 5 Dec 2018 11:15:50 +0100 Subject: [PATCH 001/208] 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/208] 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/208] 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 6861e7fbd04d4bdda38b25d8d9cd80f520deae05 Mon Sep 17 00:00:00 2001 From: Andrew Petersen Date: Wed, 12 Dec 2018 17:45:27 -0500 Subject: [PATCH 004/208] Add types for pseudo-audio-param --- types/pseudo-audio-param/index.d.ts | 47 +++++++++++++++++++ .../pseudo-audio-param-tests.ts | 9 ++++ types/pseudo-audio-param/tsconfig.json | 23 +++++++++ types/pseudo-audio-param/tslint.json | 7 +++ 4 files changed, 86 insertions(+) create mode 100644 types/pseudo-audio-param/index.d.ts create mode 100644 types/pseudo-audio-param/pseudo-audio-param-tests.ts create mode 100644 types/pseudo-audio-param/tsconfig.json create mode 100644 types/pseudo-audio-param/tslint.json diff --git a/types/pseudo-audio-param/index.d.ts b/types/pseudo-audio-param/index.d.ts new file mode 100644 index 0000000000..beaf205b7d --- /dev/null +++ b/types/pseudo-audio-param/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for pseudo-audio-param 1.3 +// Project: https://github.com/mohayonao/pseudo-audio-param/ +// Definitions by: Drew Petersen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "pseudo-audio-param" { + export = PseudoAudioParam; +} + +interface PseudoAudioParamEvent { + type: string; + time: number; +} + +/** Simulate scheduled AudioParam values */ +declare class PseudoAudioParam { + events: PseudoAudioParamEvent[]; + + constructor(defaultValue: number); + + /** + * Return scheduled value at time + */ + getValueAtTime(time: number): number; + + /** + * Apply scheduled methods to the provided audioParam. If reset is `true`, + * cancel all events of AudioParam before applying + */ + applyTo(audioParam: AudioParam, reset: boolean): PseudoAudioParam; + + setValueAtTime(value: number, time: number): PseudoAudioParam; + linearRampToValueAtTime(value: number, time: number): PseudoAudioParam; + exponentialRampToValueAtTime(value: number, time: number): PseudoAudioParam; + setTargetAtTime( + value: number, + time: number, + timeConstant: number + ): PseudoAudioParam; + setValueCurveAtTime( + values: number[], + time: number, + duration: number + ): PseudoAudioParam; + cancelScheduledValues(time: number): PseudoAudioParam; + cancelAndHoldAtTime(time: number): PseudoAudioParam; +} diff --git a/types/pseudo-audio-param/pseudo-audio-param-tests.ts b/types/pseudo-audio-param/pseudo-audio-param-tests.ts new file mode 100644 index 0000000000..0c0bfe7b90 --- /dev/null +++ b/types/pseudo-audio-param/pseudo-audio-param-tests.ts @@ -0,0 +1,9 @@ +import PseudoAudioParam = require('pseudo-audio-param'); +const p = new PseudoAudioParam(1); +const v: number = p.getValueAtTime(0.1); + +const ctx = new AudioContext(); +const gain = new GainNode(ctx); +p.applyTo(gain.gain, false); + +p.setValueAtTime(0, 1); diff --git a/types/pseudo-audio-param/tsconfig.json b/types/pseudo-audio-param/tsconfig.json new file mode 100644 index 0000000000..58c4d8e868 --- /dev/null +++ b/types/pseudo-audio-param/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pseudo-audio-param-tests.ts" + ] +} diff --git a/types/pseudo-audio-param/tslint.json b/types/pseudo-audio-param/tslint.json new file mode 100644 index 0000000000..c9579fee14 --- /dev/null +++ b/types/pseudo-audio-param/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false, + "no-declare-current-package": false + } +} From b8afa6b51d275d3902b34aa2fcc66c4fb87cbdb6 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Tue, 18 Dec 2018 07:57:24 +0100 Subject: [PATCH 005/208] 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 1ad8cd0bda8cca7d38a50f8f687e14e7863aa797 Mon Sep 17 00:00:00 2001 From: Andrew Petersen Date: Sun, 23 Dec 2018 23:04:53 -0600 Subject: [PATCH 006/208] [pseudo-audio-param] Use newer umd pattern --- types/pseudo-audio-param/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/types/pseudo-audio-param/index.d.ts b/types/pseudo-audio-param/index.d.ts index beaf205b7d..43244b79e6 100644 --- a/types/pseudo-audio-param/index.d.ts +++ b/types/pseudo-audio-param/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Drew Petersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "pseudo-audio-param" { - export = PseudoAudioParam; -} +export = PseudoAudioParam; +export as namespace PseudoAudioParam; interface PseudoAudioParamEvent { type: string; From 72e1e768f92d11ec61b25c0ff9205f1ecb74a3de Mon Sep 17 00:00:00 2001 From: Andrew Petersen Date: Sun, 23 Dec 2018 23:16:00 -0600 Subject: [PATCH 007/208] [pseudo-audio-param] Restrict to Typescript 3.0? --- types/pseudo-audio-param/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/pseudo-audio-param/index.d.ts b/types/pseudo-audio-param/index.d.ts index 43244b79e6..d1ef1dde93 100644 --- a/types/pseudo-audio-param/index.d.ts +++ b/types/pseudo-audio-param/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mohayonao/pseudo-audio-param/ // Definitions by: Drew Petersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 export = PseudoAudioParam; export as namespace PseudoAudioParam; From a623516aa78e67b507e5135869f4404bd9f91ef6 Mon Sep 17 00:00:00 2001 From: Wouter R Date: Mon, 24 Dec 2018 12:39:12 +0100 Subject: [PATCH 008/208] 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 f41cb80557e9e5bf468d7f75d1cf08635025d7f5 Mon Sep 17 00:00:00 2001 From: SirMcPotato Date: Wed, 26 Dec 2018 23:33:46 +0100 Subject: [PATCH 009/208] 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/208] 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/208] 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/208] 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/208] [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/208] 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/208] 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/208] 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/208] 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/208] 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/208] 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/208] 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 bbe324b28b9e25c2496b3a772dd5eefe211e43e3 Mon Sep 17 00:00:00 2001 From: Victor Irzak Date: Wed, 26 Dec 2018 21:35:00 -0500 Subject: [PATCH 021/208] Added Russian readme --- README.md | 8 +- README.ru.md | 353 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 357 insertions(+), 4 deletions(-) create mode 100644 README.ru.md diff --git a/README.md b/README.md index a9be0471a1..d6b8bde545 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. -*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)* +*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md) and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!* ## What are declaration files? @@ -169,10 +169,10 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN #### Lint -All new packages must be linted. To lint a package, add a `tslint.json` to that package containing +All new packages must be linted. To lint a package, add a `tslint.json` to that package containing ```js -{ - "extends": "dtslint/dt.json" +{ + "extends": "dtslint/dt.json" } ``` diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000000..b90bdeac7c --- /dev/null +++ b/README.ru.md @@ -0,0 +1,353 @@ + + +# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) + +[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +> Репозиторий для *высококачественных* определений типов TypeScript. + +Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая. + +*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).* + +## Что такое файлы декларации (файлы описания/объявления типов)? + +Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). + +## Как их получить? + +### npm + +Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например: + +```sh +npm install --save-dev @types/node +``` + +Затем типы должны автоматически включаться компилятором. +Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). + +Для пакета NPM "foo", описания будут находиться в "@types/foo". +Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/). + +Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию. +Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// `. + + +### Другие методы + +Эти методы могут быть использованы TypeScript 1.0. + +* [Typings](https://github.com/typings/typings) +* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена) +* Вручную загрузите из ветки `master` этого репозитория + +Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). + + +## Как я могу внести свой вклад? + +DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы! + +### Тестирование + +Прежде чем поделиться своим улучшением с миром, используйте его сами. + +#### Тестирование редактирования существующего пакета + +Для добавления новых функций вы можете использовать [разрешение модулей](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation). +Вы также можете напрямую редактировать типы в `node_modules/@types/foo/index.d.ts`, или скопировать их оттуда и выполнить следующие шаги. + + +#### Тестирование ногово пакета + +Добавьте к вашему `tsconfig.json`: + +```json +"baseUrl": "types", +"typeRoots": ["types"], +``` + +(Вы также можете использовать `src/types`.) +Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo". +Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа. +Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения. +После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request) +и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или +[создать новый пакет](#create-a-new-package). + + +### Запрос на принятие изменений (PR) + +После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped. + +Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`. + + +#### Изменение существующего пакета + +* `cd types/my-package-to-edit` +* Внесите изменения. Не забудьте отредактировать тесты. + Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version). +* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета. + * Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом. + * Сделайте это, добавив свое имя в конец строки, например `// Definitions by: Alice , Bob `. + * Или, если есть больше людей, это может быть многострочным + + ```typescript + // Definitions by: Alice + // Bob + // Steve + // John + ``` + +* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` in в директории пакета. + +Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить previous authors. +предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR. + + +#### Созданое нового пакета + +Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped. + +Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем. +Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM. +(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.) + +Ваш пакет должен иметь такую ​​структуру: + +| Файл | Назначение | +| ------------- | ---------------------------------------------------------------------------------------------------- | +| index.d.ts | Содержит типизацию для пакета. | +| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. | +| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. | +| tslint.json | Включает linting. | + +Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае. +Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen). + +Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`. + +Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий. + +Хороший пример пакета смотрите [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js). + + +#### Распространенные ошибки + +* Сначала следуйте советам из справочника [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). +* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела. +* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры. +* `interface Foo { new(): Foo; }`: + Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`. +* `const Class: { new(): IClass; }`: + Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`. +* `getMeAT(): T`: + Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа. + Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`. + Пример, где допустим параметр типа: `function id(value: T): T;`. + Пример, где это недопустимо: `function parseJson(json: string): T;`. + Исключение: `new Map()` все ОК. +* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`. +* `var foo: string | any`: + когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`. + В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`. + + +#### Удаление пакета + +Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы. + +Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`. + +* `typingsPackageName`: название директории, который нужно удалить. +* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия +* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации. +* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".) + +Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`. + +Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`. + + +#### Lint + +Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий + +```js +{ + "extends": "dtslint/dt.json" +} +``` + +Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например: + +```js +{ + "extends": "dtslint/dt.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "ban-types": false + } +} +``` + +(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.) + +Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$ExpectError`. + +```js +// $ExpectType void +f(1); + +// $ExpectError +f("one"); +``` + +Для получения дополнительной информации см. [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme. + +Протестируйте, запустив `npm run lint package-name` где `package-name` - это имя вашего пакета. +Этот скрипт использует [dtslint](https://github.com/Microsoft/dtslint). + + +## Часто задаваемые вопросы + +#### Какая связь между этим репозиторием и пакетами `@types` в NPM? + +Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher). + +#### Я отправил PR. Когда он сольется? + +Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR. + +#### Мой PR слит; когда будет обновлен пакет `@types` NPM? + +Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать. + +#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `` или import? + +Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import. +Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте ``. + +#### Я заметил, что у некоторых пакетов есть `package.json`. + +Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`. +`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json). +Мы не разрешаем определять другие поля, такие как "description", вручную. +Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`. + +#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`. + +Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их. + +#### Могу ли я запросить определение? + +Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). + +#### Как насчет определений типов для DOM? + +Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию. + +#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`? + +Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте. +В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html). +Не меняйте определение типа, если оно точное. +Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом. + +#### Я хочу использовать функции из TypeScript 2.1 или выше. + +В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`. + +#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию. + +Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там. +Если стандарт все еще является черновиком, добавляйте сюда. +Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке. +Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`. + +#### Я хочу обновить пакет новой старшей версии + +Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо: + +1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`. +2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии. + +Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: + +```json +{ + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "history": [ "history/v2" ] + }, + }, + "files": [ + "index.d.ts", + "history-tests.ts" + ] +} +``` + +Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии. + +Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`; +транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). + +Также, `/// ` не будет работать с отображением пути, поэтому зависимости должны использовать `import`. + +#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля? + +Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6. + +Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js. + +Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот. + +#### А как насчет областных пакетов? + +Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание. + +Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле +`tsconfig.json` для правильной ссылки на пакет с областью действия: + +```json +{ + "paths":{ + "@foo/bar": ["foo__bar"] + } +} +``` + + +#### История файлов в GitHub выглядит неполной. + +GitHub не [поддерживает](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) историю файлов для переименованных файлов. Вместо этого используйте [`git log --follow`](https://www.git-scm.com/docs/git-log). + +#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6? + +Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию. + +Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке: + +> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct + +Эту ошибку можно устранить, объединив объявление функции с пустым namespace'ом с тем же именем, но это не рекомендуется. +Это часто цитируемый [ответ с Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) по этому вопросу. + +Более целесообразно импортировать модуль, используя `import foo = require("foo");` синтаксис или использовать импорт по умолчанию, такой как `import foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых. + +## Лицензия + +Этот проект лицензирован по лицензии MIT. + +Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения. + +[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) + +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд? + +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа? 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 022/208] 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 023/208] [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 024/208] [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 025/208] 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 026/208] 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 027/208] 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 028/208] 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 029/208] 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 030/208] 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 031/208] 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 032/208] 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 033/208] 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 034/208] 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 035/208] 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 036/208] 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 037/208] 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 038/208] 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 039/208] 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 040/208] 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 041/208] [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 042/208] 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 043/208] 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 044/208] 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 045/208] [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 046/208] [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 047/208] 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 048/208] 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 049/208] 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 050/208] 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 051/208] 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 052/208] [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 053/208] 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 054/208] 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 055/208] 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 056/208] 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 057/208] 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 058/208] 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 059/208] 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 060/208] 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 061/208] 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 062/208] 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 063/208] 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 064/208] 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 065/208] 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 066/208] 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 067/208] 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 068/208] 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 069/208] 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 070/208] 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 071/208] 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 072/208] 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 073/208] 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 074/208] [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 3095a0a2660b111a3b2d795f95e2025099750efe Mon Sep 17 00:00:00 2001 From: Laurens Rietveld Date: Mon, 31 Dec 2018 19:00:12 +0100 Subject: [PATCH 075/208] N3: Added typings for synchronous parsing (#29726) * N3: Added typings for synchronous parsing * Improved signature order of parse function --- types/n3/index.d.ts | 1 + types/n3/n3-tests.ts | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/types/n3/index.d.ts b/types/n3/index.d.ts index 3d19f36d38..4a4e7812e6 100644 --- a/types/n3/index.d.ts +++ b/types/n3/index.d.ts @@ -143,6 +143,7 @@ export interface ParserOptions { export type ParseCallback = (error: Error, quad: Q, prefixes: Prefixes) => void; export interface N3Parser { + parse(input: string): Q[]; parse(input: string, callback: ParseCallback): void; } diff --git a/types/n3/n3-tests.ts b/types/n3/n3-tests.ts index 58d10892da..853308cbba 100644 --- a/types/n3/n3-tests.ts +++ b/types/n3/n3-tests.ts @@ -76,6 +76,15 @@ function test_doc_rdf_to_triples_2() { const parser5: N3.N3Parser = N3.Parser({ format: 'text/n3' }); } +function test_doc_rdf_sync_to_triples_1() { + const parser: N3.N3Parser = new N3.Parser(); + const result = parser.parse(`@prefix c: . + c:Tom a c:Cat. + c:Jerry a c:Mouse; + c:smarterThan c:Tom.`); + result.forEach((s) => console.log(s)); +} + function test_doc_rdf_stream_to_triples_1() { interface QuadBnode extends N3.BaseQuad { subject: N3.BlankNode; From 703965fef54a1df18720493e39ab255ff32f3ede Mon Sep 17 00:00:00 2001 From: Erik Kristensen Date: Mon, 31 Dec 2018 11:03:22 -0700 Subject: [PATCH 076/208] [@types/restify] Fix Callback Typing on Restify Metrics Plugin (#29785) * fix typing on restify metrics plugin * should be a function with typed arguments * adding some comments to get another build to move the PR along --- types/restify/index.d.ts | 28 +++++++++++++++++++--------- types/restify/v5/index.d.ts | 4 ++-- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index a035a87396..1bff23e8ea 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1417,22 +1417,32 @@ export namespace plugins { */ function throttle(options?: ThrottleOptions): RequestHandler; - interface MetricsCallback { + type MetricsCallback = ( /** * An error if the request had an error */ - err: Error; + err: Error, - metrics: MetricsCallbackOptions; + /** + * Object that contains the various metrics that are returned + */ + metrics: MetricsCallbackOptions, - req: Request; - res: Response; + /** + * The request obj + */ + req: Request, + + /** + * The response obj + */ + res: Response, /** * The route obj that serviced the request */ - route: Route; - } + route: Route, + ) => void; type TMetricsCallback = 'close' | 'aborted' | undefined; @@ -1495,13 +1505,13 @@ export namespace plugins { * Listens to the server's after event and emits information about that request (5.x compatible only). * * ``` - * server.on('after', plugins.metrics( (err, metrics) => + * server.on('after', plugins.metrics({ server }, (err, metrics, req, res, route) => * { * // metrics is an object containing information about the request * })); * ``` */ - function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; + function metrics(opts: { server: Server }, callback: MetricsCallback): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable diff --git a/types/restify/v5/index.d.ts b/types/restify/v5/index.d.ts index 11664c60cf..0ff2abfae4 100644 --- a/types/restify/v5/index.d.ts +++ b/types/restify/v5/index.d.ts @@ -1251,13 +1251,13 @@ export namespace plugins { * Listens to the server's after event and emits information about that request (5.x compatible only). * * ``` - * server.on('after', plugins.metrics( (err, metrics) => + * server.on('after', plugins.metrics({ server }, (err, metrics, req, res, route) => * { * // metrics is an object containing information about the request * })); * ``` */ - function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; + function metrics(opts: { server: Server }, callback: MetricsCallback): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable From 6d9584582e4a991236fa1e10a0dd3ee056bc9705 Mon Sep 17 00:00:00 2001 From: Shai Reznik Date: Mon, 31 Dec 2018 20:06:28 +0200 Subject: [PATCH 077/208] [jasmine-given] add fail function to done function definition (#29933) --- types/jasmine-given/index.d.ts | 20 ++++++++++----- types/jasmine-given/jasmine-given-tests.ts | 30 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/types/jasmine-given/index.d.ts b/types/jasmine-given/index.d.ts index e2b630eccd..df2fe424a9 100644 --- a/types/jasmine-given/index.d.ts +++ b/types/jasmine-given/index.d.ts @@ -3,9 +3,17 @@ // Definitions by: Shai Reznik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function Given(func: (done?: () => void) => void): void; -declare function When(func: (done?: () => void) => void): void; -declare function Then(func: (done?: () => void) => void): void; -declare function Then(label: string, func: (done?: () => void) => void): void; -declare function And(func: (done?: () => void) => void): void; -declare function Invariant(func: (done?: () => void) => void): void; +/** Action method that should be called when the async work is complete */ +interface DoneFn { + (): void; + + /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */ + fail: (message?: Error | string) => void; +} + +declare function Given(func: (done?: DoneFn) => void): void; +declare function When(func: (done?: DoneFn) => void): void; +declare function Then(func: (done?: DoneFn) => void): void; +declare function Then(label: string, func: (done?: DoneFn) => void): void; +declare function And(func: (done?: DoneFn) => void): void; +declare function Invariant(func: (done?: DoneFn) => void): void; diff --git a/types/jasmine-given/jasmine-given-tests.ts b/types/jasmine-given/jasmine-given-tests.ts index 7658502b68..10a6b824fe 100644 --- a/types/jasmine-given/jasmine-given-tests.ts +++ b/types/jasmine-given/jasmine-given-tests.ts @@ -39,3 +39,33 @@ Invariant((done) => { done(); } }); + +Given((done) => { + if (done) { + done.fail(); + } +}); + +When((done) => { + if (done) { + done.fail(); + } +}); + +Then('expected condition 2', (done) => { + if (done) { + done.fail(); + } +}); + +And((done) => { + if (done) { + done.fail(); + } +}); + +Invariant((done) => { + if (done) { + done.fail(); + } +}); From 9272fc163770b21cfe1ff7ffe4ce5329db07314d Mon Sep 17 00:00:00 2001 From: Oscar Busk Date: Mon, 31 Dec 2018 19:13:42 +0100 Subject: [PATCH 078/208] [d3-cloud] Support import syntax (#30479) * Allow importing from `d3-cloud` * Modify export to be CommonJS --- types/d3-cloud/d3-cloud-tests.ts | 9 +++++++++ types/d3-cloud/index.d.ts | 2 ++ 2 files changed, 11 insertions(+) diff --git a/types/d3-cloud/d3-cloud-tests.ts b/types/d3-cloud/d3-cloud-tests.ts index 862b7f0d82..e3bffed4cb 100644 --- a/types/d3-cloud/d3-cloud-tests.ts +++ b/types/d3-cloud/d3-cloud-tests.ts @@ -1,3 +1,12 @@ +import d3Cloud = require('./index.d'); +import d3 = require('d3'); + +// $ExpectType Cloud +d3Cloud(); + +// $ExpectType Cloud +d3.layout.cloud(); + interface ICompTextSize{ text:string; size:number; diff --git a/types/d3-cloud/index.d.ts b/types/d3-cloud/index.d.ts index 70e2140bd5..fdf2dbc719 100644 --- a/types/d3-cloud/index.d.ts +++ b/types/d3-cloud/index.d.ts @@ -5,6 +5,8 @@ import * as d3 from 'd3'; +export = d3.layout.cloud; + declare module 'd3' { namespace layout { export function cloud(): Cloud; From d8efd10d1a84680dddee881ad42a8fda51910b13 Mon Sep 17 00:00:00 2001 From: Joshua Searles Date: Mon, 31 Dec 2018 13:15:15 -0500 Subject: [PATCH 079/208] Update Autobahn Connection with properties isRetrying and session (#30526) * Update Autobahn Connection with properties isRetrying and session * Adjust dtheader, per review --- types/autobahn/autobahn-tests.ts | 4 +++- types/autobahn/index.d.ts | 8 +++++--- types/autobahn/tslint.json | 1 - 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/types/autobahn/autobahn-tests.ts b/types/autobahn/autobahn-tests.ts index d753e960fe..8f05c25141 100644 --- a/types/autobahn/autobahn-tests.ts +++ b/types/autobahn/autobahn-tests.ts @@ -43,5 +43,7 @@ function test_client() { }); }; - connection.open(); + if (!connection.isOpen && !connection.isRetrying && connection.session == null) { + connection.open(); + } } diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index c62f6115af..7a518e0fd4 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for AutobahnJS v0.9.7 +// Type definitions for AutobahnJS 0.9 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -191,7 +191,9 @@ declare namespace autobahn { constructor(options?: IConnectionOptions); isOpen: boolean; - + isRetrying: boolean; + session?: Session; + open(): void; close(reason?: string, message?: string): void; diff --git a/types/autobahn/tslint.json b/types/autobahn/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/autobahn/tslint.json +++ b/types/autobahn/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, From fa697d0de0e6527d1a82710644caeeb405e67526 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 23 Dec 2018 21:06:10 +0100 Subject: [PATCH 080/208] [@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 8acdd28c1e4e9c11af416e82ad9dee2748172511 Mon Sep 17 00:00:00 2001 From: Youngrok Kim Date: Tue, 1 Jan 2019 03:17:47 +0900 Subject: [PATCH 081/208] [range-parser] replace const enum with plain enum (#30680) * description * --isolatedModules fix * replace const enum with plain enum From deb6f8ae481c2f96e8ae71cbd7ba0394b467cc1f Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 23 Dec 2018 19:40:04 +0100 Subject: [PATCH 082/208] [@keyv/sqlite] Add types --- types/keyv__sqlite/index.d.ts | 33 ++++++++++++++++++++++++ types/keyv__sqlite/keyv__sqlite-tests.ts | 12 +++++++++ types/keyv__sqlite/tsconfig.json | 28 ++++++++++++++++++++ types/keyv__sqlite/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100644 types/keyv__sqlite/index.d.ts create mode 100644 types/keyv__sqlite/keyv__sqlite-tests.ts create mode 100644 types/keyv__sqlite/tsconfig.json create mode 100644 types/keyv__sqlite/tslint.json diff --git a/types/keyv__sqlite/index.d.ts b/types/keyv__sqlite/index.d.ts new file mode 100644 index 0000000000..3a59e7b2b7 --- /dev/null +++ b/types/keyv__sqlite/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for @keyv/sqlite 2.0 +// Project: https://github.com/lukechilds/keyv-sqlite +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { EventEmitter } from 'events'; + +export = KeyvSqlite; + +declare class KeyvSqlite extends EventEmitter implements Store { + readonly ttlSupport: false; + namespace?: string; + + constructor(options?: KeyvSqlite.Options); + + get(key: string): Promise; + set(key: string, value: string | undefined): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvSqlite { + interface Options { + uri?: string; + busyTimeout?: number; + table?: string; + keySize?: number; + } +} diff --git a/types/keyv__sqlite/keyv__sqlite-tests.ts b/types/keyv__sqlite/keyv__sqlite-tests.ts new file mode 100644 index 0000000000..e109dbf4a1 --- /dev/null +++ b/types/keyv__sqlite/keyv__sqlite-tests.ts @@ -0,0 +1,12 @@ +import Keyv = require('keyv'); +import KeyvSqlite = require('@keyv/sqlite'); + +new Keyv('sqlite://path/to/database.sqlite', { table: 'cache' }); + +new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite' }); +new KeyvSqlite({ busyTimeout: 10000 }); +new KeyvSqlite({ table: 'cache' }); +new KeyvSqlite({ keySize: 100 }); + +const sqlite = new KeyvSqlite({ uri: 'sqlite://path/to/database.sqlite' }); +new Keyv({ store: sqlite }); diff --git a/types/keyv__sqlite/tsconfig.json b/types/keyv__sqlite/tsconfig.json new file mode 100644 index 0000000000..5546f7acef --- /dev/null +++ b/types/keyv__sqlite/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/sqlite": [ + "keyv__sqlite" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__sqlite-tests.ts" + ] +} diff --git a/types/keyv__sqlite/tslint.json b/types/keyv__sqlite/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__sqlite/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 499c5aaf02106edffa61cc1a018a2240d60712f1 Mon Sep 17 00:00:00 2001 From: Mihail Novikov Date: Mon, 31 Dec 2018 21:22:13 +0300 Subject: [PATCH 083/208] Add types for react-simple-maps (#31221) * Add types for react-simple-maps * [@types/react-simple-maps] Add test file --- types/react-simple-maps/index.d.ts | 125 ++++++++++++++++++ .../react-simple-maps-tests.tsx | 70 ++++++++++ types/react-simple-maps/tsconfig.json | 17 +++ types/react-simple-maps/tslint.json | 1 + 4 files changed, 213 insertions(+) create mode 100644 types/react-simple-maps/index.d.ts create mode 100644 types/react-simple-maps/react-simple-maps-tests.tsx create mode 100644 types/react-simple-maps/tsconfig.json create mode 100644 types/react-simple-maps/tslint.json diff --git a/types/react-simple-maps/index.d.ts b/types/react-simple-maps/index.d.ts new file mode 100644 index 0000000000..cb146c372f --- /dev/null +++ b/types/react-simple-maps/index.d.ts @@ -0,0 +1,125 @@ +// Type definitions for react-simple-maps 0.12 +// Project: https://github.com/zcreativelabs/react-simple-maps#readme +// Definitions by: Novikov Mihail +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export type Point = [number, number]; + +export interface Line { + coordinates: { + start: Point; + end: Point; + }; +} + +export interface ComposableMapProps { + width?: number; + height?: number; + projection?: string | (() => void); + projectionConfig?: { + scale?: number; + xOffset?: number; + yOffset?: number; + rotation?: number[]; + precision?: number; + }; + style?: React.CSSProperties; + defs?: SVGDefsElement; +} + +export interface ZoomableProps { + zoom?: number; + center?: Point; + style?: React.CSSProperties; + onMoveStart?: (currentCenter: Point) => void; + onMoveEnd?: (newCenter: Point) => void; +} + +export interface ZoomableGroupProps extends ZoomableProps { + disablePanning?: boolean; +} + +export interface GeographiesProps { + disableOptimization?: boolean; + geography?: string | { [key: string]: any } | string[]; + children?: (geographies: object[], projection: (point: Point) => void) => void; +} + +export interface GeographyProps { + cacheId?: number | string | null; + precision?: number; + round?: boolean; + geography?: object; + projection?: (point: Point) => void; + tabable?: boolean; + style?: { + default?: React.CSSProperties; + hover?: React.CSSProperties; + pressed?: React.CSSProperties; + }; +} + +export interface MarkerProps { + marker?: { + coordinates: Point; + }; + tabable?: boolean; + style?: { + default?: React.CSSProperties; + hover?: React.CSSProperties; + pressed?: React.CSSProperties; + }; + preserveMarkerAspect?: boolean; +} + +export interface AnnotationProps { + subject?: Point; + dx?: number; + dy?: number; + zoom?: number; + stroke?: string; + strokeWidth?: number; + style?: React.CSSProperties; + markerEnd?: string; + curve?: number; +} + +export interface GraticuleProps { + step?: Point; + round?: boolean; + precision?: number; + outline?: boolean; + stroke?: string; + fill?: string; + style?: React.CSSProperties; + disableOptimization?: boolean; + Globe?: boolean; +} + +export interface LineProps { + line?: Line; + tabable?: boolean; + style?: { + default?: React.CSSProperties; + hover?: React.CSSProperties; + pressed?: React.CSSProperties; + }; + preserveMarkerAspect?: boolean; + buildPath?: (start: Point, end: Point, line: Line) => string; +} + +export class ComposableMap extends React.Component {} +export class ZoomableGroup extends React.Component {} +export class ZoomableGlobe extends React.Component {} +export class Geographies extends React.Component {} +export class Geography extends React.Component {} +export class Markers extends React.Component {} +export class Marker extends React.Component {} +export class Annotations extends React.Component {} +export class Annotation extends React.Component {} +export class Graticule extends React.Component {} +export class Lines extends React.Component {} +export class Line extends React.Component {} diff --git a/types/react-simple-maps/react-simple-maps-tests.tsx b/types/react-simple-maps/react-simple-maps-tests.tsx new file mode 100644 index 0000000000..9d8734014d --- /dev/null +++ b/types/react-simple-maps/react-simple-maps-tests.tsx @@ -0,0 +1,70 @@ +import * as React from 'react'; +import { + ComposableMap, + Geographies, + Geography, + Marker, + Markers, + ZoomableGroup, +} from 'react-simple-maps'; + +const Map = () => ( + + + + {(geographies, projection) => + geographies.map((geography, index) => ( + + )) + } + + + + + + + + +); diff --git a/types/react-simple-maps/tsconfig.json b/types/react-simple-maps/tsconfig.json new file mode 100644 index 0000000000..443d87aff4 --- /dev/null +++ b/types/react-simple-maps/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "jsx": "react", + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-simple-maps-tests.tsx"] +} diff --git a/types/react-simple-maps/tslint.json b/types/react-simple-maps/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-simple-maps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1683b160b980e2154b8e804881cfe8f5c3bab490 Mon Sep 17 00:00:00 2001 From: Robert Bullen Date: Mon, 31 Dec 2018 12:23:59 -0600 Subject: [PATCH 084/208] yup: ObjectSchema.shape() should support type intersections (#31290) * - change ObjectSchema.shape() to ObjectSchema.shape() - changed Schema.validate*() to accept any type - made declaration of Ref more restrictive - bumped definitions version * Addressed PR feedback: - refined `ObjectSchema.shape()` with `Shape` - added a few more test cases --- types/yup/index.d.ts | 55 +++++++++++++++++++++++++++++++++--------- types/yup/yup-tests.ts | 53 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 92 insertions(+), 16 deletions(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 924f6f5019..8632968433 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -6,6 +6,7 @@ // Sindre Seppola // Yash Kulshrestha // Vincent Pizzo +// Robert Bullen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -58,12 +59,12 @@ export interface Schema { meta(): any; describe(): SchemaDescription; concat(schema: this): this; - validate(value: T, options?: ValidateOptions): Promise; - validateSync(value: T, options?: ValidateOptions): T; + validate(value: any, options?: ValidateOptions): Promise; + validateSync(value: any, options?: ValidateOptions): T; validateAt(path: string, value: T, options?: ValidateOptions): Promise; validateSyncAt(path: string, value: T, options?: ValidateOptions): T; - isValid(value: T, options?: any): Promise; - isValidSync(value: T, options?: any): boolean; + isValid(value: any, options?: any): Promise; + isValidSync(value: any, options?: any): value is T; cast(value: any, options?: any): T; isType(value: any): value is T; strict(isStrict: boolean): this; @@ -170,16 +171,25 @@ export interface ArraySchema extends Schema { compact(rejector?: (value: any) => boolean): ArraySchema; } +export type ObjectSchemaDefinition = { [field in keyof T]: Schema | Ref }; + +/** + * Merges two interfaces. For properties in common, property types from `U` trump those of `T`. + * This is conducive to the functionality of + * [yup's `object.shape()` method](https://www.npmjs.com/package/yup#objectshapefields-object-nosortedges-arraystring-string-schema). + */ +export type Shape = { [P in keyof T]: P extends keyof U ? U[P] : T[P] } & U; + export interface ObjectSchemaConstructor { - (fields?: { [field in keyof T]: Schema }): ObjectSchema; + (fields?: ObjectSchemaDefinition): ObjectSchema; new (): ObjectSchema<{}>; } -export interface ObjectSchema extends Schema { - shape( - fields: { [field in keyof T]: Schema }, +export interface ObjectSchema extends Schema { + shape( + fields: ObjectSchemaDefinition, noSortEdges?: Array<[string, string]> - ): ObjectSchema; + ): ObjectSchema>; from(fromKey: string, toKey: string, alias?: boolean): ObjectSchema; noUnknown(onlyKnownKeys?: boolean, message?: TestOptionsMessage): ObjectSchema; transformKeys(callback: (key: any) => any): void; @@ -303,8 +313,31 @@ export interface ValidationError { params?: object; } -export interface Ref { - [key: string]: any; +// It is tempting to declare `Ref` very simply, but there are problems with these approaches: +// +// * `type Ref = Record;` - This is essentially how it was originally declared, but +// just about any object satisfies this contract, which makes the type declaration too loose to +// be useful. +// +// * `type Ref = object;` - This is a variation on the previous bullet in that it is too loose. +// +// * `class Ref {}` - This is yet another variation that is too loose. +// +// * `type Ref = void;` - This works and the emitted JavaScript is just fine, but it results in some +// confusing IntelliSense, e.g it looks like the `ref()` returns `void`, which is not the case. +// +// The solution is twofold. 1.) Declare it as a class with a private constructor to prevent it from +// being instantiated by anything but the `ref()` factory function, and; 2.) declare a private +// readonly property (that yup actually places on the prototype) to force it to be structurally +// incompatible with any other object type. + +/** + * `Ref` is an opaque type that is internal to yup. Creating a `Ref` instance is accomplished via the `ref()` factory + * function. + */ +export class Ref { + private constructor(); + private readonly __isYupRef: true; } // tslint:disable-next-line:no-empty-interface diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index 1c13d6566f..cd661a2521 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -16,13 +16,13 @@ import { } from "yup"; // reach function -let schema = yup.object().shape({ +const schema1 = yup.object().shape({ nested: yup.object().shape({ arr: yup.array().of(yup.object().shape({ num: yup.number().max(4) })) }) }); -reach(schema, "nested.arr.num"); -reach(schema, "nested.arr[].num"); +reach(schema1, "nested.arr.num"); +reach(schema1, "nested.arr[].num"); // addMethod function yup.addMethod(yup.number, "minimum", function( @@ -41,7 +41,7 @@ yup.addMethod(yup.date, "newMethod", function( }); // ref function -schema = yup.object().shape({ +const schema2 = yup.object().shape({ baz: yup.ref("foo.bar"), foo: yup.object().shape({ bar: yup.string() @@ -49,7 +49,16 @@ schema = yup.object().shape({ x: yup.ref("$x") }); -schema.cast({ foo: { bar: "boom" } }, { context: { x: 5 } }); +let ref: yup.Ref = yup.ref("foo.bar"); + +// $ExpectError +ref = {}; + +// $ExpectError +ref = { __isYupRef: true }; + +// cast function +schema2.cast({ foo: { bar: "boom" } }, { context: { x: 5 } }); // lazy function const node: ObjectSchema = yup.object().shape({ @@ -459,6 +468,40 @@ const testObject: MyInterface = { typedSchema.validateSync(testObject); // $ExpectType MyInterface +// Shape and shape function +interface AB { + a: string; + b: number; +} + +interface BC { + b: string; + c: number; +} + +interface ExpectedABC { + a: string; + b: string; + c: number; +} + +const expectedAbc: ExpectedABC = { + a: 'qwerty', + b: 'asdfg', + c: 123 +}; +const actualAbc: yup.Shape = expectedAbc; + +const definitionAB: yup.ObjectSchemaDefinition = { + a: yup.string(), + b: yup.number() +}; +const definitionBC: yup.ObjectSchemaDefinition = { + b: yup.string(), + c: yup.number() +}; +const combinedSchema = yup.object(definitionAB).shape(definitionBC); // $ExpectType ObjectSchema> + // $ExpectError yup.object({ stringField: yup.string().required(), From 2d5bc81771eee41c60550765166af74018997771 Mon Sep 17 00:00:00 2001 From: Marco Lanaro Date: Mon, 31 Dec 2018 18:29:48 +0000 Subject: [PATCH 085/208] Add types for distributions (#31472) * Add types for distributions * Fix import --- types/distributions/distributions-tests.ts | 17 +++++++++++++++ types/distributions/index.d.ts | 18 ++++++++++++++++ types/distributions/tsconfig.json | 24 ++++++++++++++++++++++ types/distributions/tslint.json | 1 + 4 files changed, 60 insertions(+) create mode 100644 types/distributions/distributions-tests.ts create mode 100644 types/distributions/index.d.ts create mode 100644 types/distributions/tsconfig.json create mode 100644 types/distributions/tslint.json diff --git a/types/distributions/distributions-tests.ts b/types/distributions/distributions-tests.ts new file mode 100644 index 0000000000..04cb1b65bb --- /dev/null +++ b/types/distributions/distributions-tests.ts @@ -0,0 +1,17 @@ +import * as distributions from 'distributions'; + +const normal = distributions.Normal(); +normal.cdf(0); +normal.pdf(0); +normal.inv(0); +normal.mean(); +normal.median(); +normal.variance(); + +const uniform = distributions.Uniform(); +uniform.cdf(0); +uniform.pdf(0); +uniform.inv(0); +uniform.mean(); +uniform.median(); +uniform.variance(); diff --git a/types/distributions/index.d.ts b/types/distributions/index.d.ts new file mode 100644 index 0000000000..cdfbc93c6b --- /dev/null +++ b/types/distributions/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for distributions 2.0 +// Project: https://github.com/AndreasMadsen/distributions +// Definitions by: Marco Lanaro +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function Normal(mean?: number, sd?: number): Distribution; +export function Studentt(df: number): Distribution; +export function Uniform(a?: number, b?: number): Distribution; +export function Binomial(properbility: number, size: number): Distribution; + +export interface Distribution { + pdf: (x: number) => number; + cdf: (x: number) => number; + inv: (p: number) => number; + mean: () => number; + median: () => number; + variance: () => number; +} diff --git a/types/distributions/tsconfig.json b/types/distributions/tsconfig.json new file mode 100644 index 0000000000..995b1007ef --- /dev/null +++ b/types/distributions/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "distributions-tests.ts" + ] +} diff --git a/types/distributions/tslint.json b/types/distributions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/distributions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6b9f1df1d277cae914083accc834471477b313fb Mon Sep 17 00:00:00 2001 From: David Gomes Date: Mon, 31 Dec 2018 18:33:29 +0000 Subject: [PATCH 086/208] Fix type of Redux Form event handlers. (#31607) * Fix type of Redux Form event handlers. * Rename `fieldName` to `name` to keep flow type definitions consistent with Redux Form naming. Co-Authored-By: davidgomes * Adds the missing name parameter to the onFocus and onDragStart event handlers in redux-form. https://redux-form.com/7.4.2/docs/api/field.md/#-code-onblur-event-newvalue-previousvalue-name-gt-void-code-optional- https://redux-form.com/7.4.2/docs/api/field.md/#-code-ondragstart-event-name-gt-void-code-optional- Co-Authored-By: davidgomes * Removes weird space I added accidentally. --- types/redux-form/lib/Field.d.ts | 4 ++-- types/redux-form/redux-form-tests.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index c303f0d5c3..87a8947717 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -16,8 +16,8 @@ export type Formatter = (value: any, name: string) => any; export type Parser = (value: any, name: string) => any; export type Validator = (value: any, allValues?: any, props?: any, name?: any) => any; -export type EventHandler = (event: Event) => void; -export type EventWithDataHandler = (event?: Event, newValue?: any, previousValue?: any) => void; +export type EventHandler = (event: Event, name?: string) => void; +export type EventWithDataHandler = (event?: Event, newValue?: any, previousValue?: any, name?: string) => void; export interface EventOrValueHandler extends EventHandler { (value: any): void; diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 70fb1f4e13..562b5df624 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -279,8 +279,8 @@ const Test = reduxForm({ {}} - onBlur={(event, newValue, previousValue) => {}} + onChange={(event, newValue, previousValue, fieldName) => {}} + onBlur={(event, newValue, previousValue, fieldName) => {}} /> Date: Mon, 31 Dec 2018 12:35:34 -0600 Subject: [PATCH 087/208] [@types/koa]: Parameterize `Context` and `Application`. (#31704) * [@types/koa]: Parameterize `Context` and `Application`. Currently, `ctx.state` is `any`, and `ctx` itself allows any fields to be inside `Context`. That's essentially 2 places where developers can add their custom properties, and would be great to opt-in into more typesafe approach than it's currently is. What if we parameterize `Context` and `Application` with 2 types - one will define `ctx.state`, and another - fields in `Context`? Then, if you chain `use`, TypeScript will infer the types properly for your middlewares. Like: ```typescript interface NewContext { orgh: string; } interface FooState { foo: string; } interface BarState { bar: string; } async function fooMiddleware( ctx: Koa.Context, next: () => Promise ): Promise { ctx.state.foo = "foo"; await next(); } async function barMiddleware( ctx: Koa.Context, next: () => Promise ): Promise { ctx.state.bar = "bar"; await next(); } const app = new Koa<{}, {}>() .use(fooMiddleware) .use(barMiddleware) .use<{}, NewContext>(async (ctx, next) => { // Here ctx is inferred as Koa.Context ctx.orgh = "bazinga"; await next(); }) .use(async (ctx, next) => { // Here ctx is inferred as Koa.Context await next(); }); // `app` here is `Koa` app.listen(3000); ``` So, if you define `const app = new Koa<{}, {}>()`, then you'll opt-in into "typesafe" Koa Context. But if you do just `const app = new Koa()`, you still will have `ctx.state: any`, like before. So, it should be backwards-compatible. But even in this case you can specify what the `ctx` is inside the middlewares, like: ```typescript const app2 = new Koa(); app2.use(fooMiddleware); app2.use(async (ctx, next) => { // `ctx.state` here is inferred as `any` ctx.state.prop = "Some Prop"; await next(); }); app2.use(async (ctx: Koa.Context<{}, NewContext>, next) => { ctx.orgh = "oh yeah"; await next(); }); app2.use(async (ctx: Koa.Context, next) => { ctx.state.foo = "Yay"; await next(); }); ``` What do you think? * Rename new `Context` to `ParameterizedContext` So that all the old hacks with declaration merging of Koa's `Context` wouldn't break. * Fix the build * Use Context instead of ParameterizedContext when possible --- types/koa-useragent/koa-useragent-tests.ts | 2 +- types/koa/index.d.ts | 24 +++++++++++++--------- types/koa/koa-tests.ts | 17 ++++++++------- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/types/koa-useragent/koa-useragent-tests.ts b/types/koa-useragent/koa-useragent-tests.ts index 579983786c..594b9b2206 100644 --- a/types/koa-useragent/koa-useragent-tests.ts +++ b/types/koa-useragent/koa-useragent-tests.ts @@ -5,7 +5,7 @@ const app = new Koa(); app.use(userAgent); -app.use((ctx, next) => { +app.use((ctx: Koa.Context, next) => { ctx.userAgent.isAuthoritative; // $ExpectType boolean ctx.userAgent.isMobile; // $ExpectType boolean ctx.userAgent.isTablet; // $ExpectType boolean diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index 802d6a242f..cc0fa86141 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -431,12 +431,12 @@ declare interface ContextDelegatedResponse { flushHeaders(): void; } -declare class Application extends EventEmitter { +declare class Application extends EventEmitter { proxy: boolean; - middleware: Application.Middleware[]; + middleware: Application.Middleware[]; subdomainOffset: number; env: string; - context: Application.BaseContext; + context: Application.BaseContext & CustomT; request: Application.BaseRequest; response: Application.BaseResponse; silent: boolean; @@ -497,7 +497,9 @@ declare class Application extends EventEmitter { * * Old-style middleware will be converted. */ - use(middleware: Application.Middleware): this; + use( + middleware: Application.Middleware, + ): Application; /** * Return a request handler callback @@ -510,10 +512,10 @@ declare class Application extends EventEmitter { * * @api private */ - createContext( + createContext( req: IncomingMessage, res: ServerResponse, - ): Application.Context; + ): Application.ParameterizedContext; /** * Default error handler. @@ -524,7 +526,7 @@ declare class Application extends EventEmitter { } declare namespace Application { - type Middleware = compose.Middleware; + type Middleware = compose.Middleware>; interface BaseRequest extends ContextDelegatedRequest { /** @@ -684,7 +686,7 @@ declare namespace Application { request: Request; } - interface Context extends BaseContext { + type ParameterizedContext = BaseContext & { app: Application; request: Request; response: Response; @@ -693,12 +695,14 @@ declare namespace Application { originalUrl: string; cookies: Cookies; accept: accepts.Accepts; - state: any; + state: StateT; /** * To bypass Koa's built-in response handling, you may explicitly set `ctx.respond = false;` */ respond?: boolean; - } + } & CustomT; + + interface Context extends ParameterizedContext {} } export = Application; diff --git a/types/koa/koa-tests.ts b/types/koa/koa-tests.ts index 2ddf9b41e2..c3d29298be 100644 --- a/types/koa/koa-tests.ts +++ b/types/koa/koa-tests.ts @@ -1,19 +1,18 @@ import Koa = require("koa"); -declare module 'koa' { - export interface BaseContext { - db(): void; - } - export interface Context { - user: {}; - } +interface DbBaseContext { + db(): void; } -const app = new Koa(); +interface UserContext { + user: {}; +} + +const app = new Koa<{}, DbBaseContext>(); app.context.db = () => {}; -app.use(async ctx => { +app.use<{}, UserContext>(async ctx => { console.log(ctx.db); ctx.user = {}; }); From a0f4fe7299d3e50cdf1ef79c5cddd09f5cb8b679 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Mon, 31 Dec 2018 18:43:36 +0000 Subject: [PATCH 088/208] react-helmet: add link and meta prop types (#31802) * Add missing semicolon * Add link and meta prop types --- types/react-helmet/index.d.ts | 8 ++++++-- types/react-helmet/react-helmet-tests.tsx | 7 ++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/types/react-helmet/index.d.ts b/types/react-helmet/index.d.ts index cecb86e12d..0a38f57c10 100644 --- a/types/react-helmet/index.d.ts +++ b/types/react-helmet/index.d.ts @@ -6,6 +6,10 @@ import * as React from "react"; +type LinkProps = JSX.IntrinsicElements['link']; + +type MetaProps = JSX.IntrinsicElements['meta']; + export interface HelmetProps { async?: boolean; base?: any; @@ -15,8 +19,8 @@ export interface HelmetProps { encodeSpecialCharacters?: boolean; htmlAttributes?: any; onChangeClientState?: (newState: any) => void; - link?: Array; - meta?: Array; + link?: LinkProps[]; + meta?: MetaProps[]; noscript?: Array; script?: Array; style?: Array; diff --git a/types/react-helmet/react-helmet-tests.tsx b/types/react-helmet/react-helmet-tests.tsx index ef2939a985..8f1a37f539 100644 --- a/types/react-helmet/react-helmet-tests.tsx +++ b/types/react-helmet/react-helmet-tests.tsx @@ -101,4 +101,9 @@ function HTML() { font-size: 12px; } `} - +; + +// $ExpectError +; +// $ExpectError +; From 44edbc65edf8ab214eefa483c35201fec0b9e9db Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 31 Dec 2018 18:48:38 +0000 Subject: [PATCH 089/208] [boxen] Add types (#31812) --- types/boxen/boxen-tests.ts | 37 ++++++++++++ types/boxen/index.d.ts | 114 +++++++++++++++++++++++++++++++++++++ types/boxen/tsconfig.json | 23 ++++++++ types/boxen/tslint.json | 1 + 4 files changed, 175 insertions(+) create mode 100644 types/boxen/boxen-tests.ts create mode 100644 types/boxen/index.d.ts create mode 100644 types/boxen/tsconfig.json create mode 100644 types/boxen/tslint.json diff --git a/types/boxen/boxen-tests.ts b/types/boxen/boxen-tests.ts new file mode 100644 index 0000000000..303e5dd7fa --- /dev/null +++ b/types/boxen/boxen-tests.ts @@ -0,0 +1,37 @@ +import boxen = require('boxen'); + +boxen('unicorn'); // $ExpectType string +boxen('unicorn', { borderColor: 'black' }); // $ExpectType string +boxen('unicorn', { borderStyle: 'double' }); // $ExpectType string +boxen('unicorn', { borderStyle: 'foo' }); // $ExpectError +// $ExpectType string +boxen('unicorn', { + borderStyle: { + topLeft: '+', + topRight: '+', + bottomLeft: '+', + bottomRight: '+', + horizontal: '-', + vertical: '|', + }, +}); +boxen('unicorn', { dimBorder: true }); // $ExpectType string +boxen('unicorn', { padding: 1 }); // $ExpectType string +boxen('unicorn', { padding: { top: 1 } }); // $ExpectType string +boxen('unicorn', { padding: { right: 1 } }); // $ExpectType string +boxen('unicorn', { padding: { bottom: 1 } }); // $ExpectType string +boxen('unicorn', { padding: { left: 1 } }); // $ExpectType string +boxen('unicorn', { margin: 1 }); // $ExpectType string +boxen('unicorn', { margin: { top: 1 } }); // $ExpectType string +boxen('unicorn', { margin: { right: 1 } }); // $ExpectType string +boxen('unicorn', { margin: { bottom: 1 } }); // $ExpectType string +boxen('unicorn', { margin: { left: 1 } }); // $ExpectType string +boxen('unicorn', { float: 'right' }); // $ExpectType string +boxen('unicorn', { float: 'center' }); // $ExpectType string +boxen('unicorn', { float: 'left' }); // $ExpectType string +boxen('unicorn', { float: 'foo' }); // $ExpectError +boxen('unicorn', { backgroundColor: 'white' }); // $ExpectType string +boxen('unicorn', { align: 'left' }); // $ExpectType string +boxen('unicorn', { align: 'center' }); // $ExpectType string +boxen('unicorn', { align: 'right' }); // $ExpectType string +boxen('unicorn', { align: 'foo' }); // $ExpectError diff --git a/types/boxen/index.d.ts b/types/boxen/index.d.ts new file mode 100644 index 0000000000..94b68bb5c7 --- /dev/null +++ b/types/boxen/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for boxen 2.1 +// Project: https://github.com/sindresorhus/boxen#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { BoxDefinition, BoxNames } from 'cli-boxes'; + +export = boxen; + +/** + * Create boxes in the terminal + * @param input Text inside the box. + */ +declare function boxen(input: string, options?: boxen.Options): string; + +declare namespace boxen { + interface Options { + /** + * Color of the box border. + * Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000` + */ + borderColor?: string; + + /** + * Style of the box border. + * Can be any of the above predefined styles or an object. + * + * Predefined values: + * - `single` + * ``` + * ┌───┐ + * │foo│ + * └───┘ + * ``` + * - `double` + * ``` + * ╔═══╗ + * ║foo║ + * ╚═══╝ + * ``` + * - `round` (`single` sides with round corners) + * ``` + * ╭───╮ + * │foo│ + * ╰───╯ + * ``` + * - `single-double` (`single` on top and bottom, `double` on right and left) + * ``` + * ╓───╖ + * ║foo║ + * ╙───╜ + * ``` + * - `double-single` (`double` on top and bottom, `single` on right and left) + * ``` + * ╒═══╕ + * │foo│ + * ╘═══╛ + * ``` + * - `classic` + * ``` + * +---+ + * |foo| + * +---+ + * ``` + */ + borderStyle?: BoxNames | BoxDefinition; + + /** + * Reduce opacity of the border. + * @default false + */ + dimBorder?: boolean; + + /** + * Space between the text and box border. + * When a number is specified, the left/right padding is 3 times the top/bottom to make it look nice. + * @default 0 + */ + padding?: number | PositionOptions; + + /** + * Space around the box. + * When a number is specified, the left/right margin is 3 times the top/bottom to make it look nice. + * @default 0 + */ + margin?: number | PositionOptions; + + /** + * Float the box on the available terminal screen space. + * @default 'left' + */ + float?: 'right' | 'center' | 'left'; + + /** + * Color of the background. + * Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000` + */ + backgroundColor?: string; + + /** + * Align the text in the box based on the widest line. + * @default 'left' + */ + align?: 'left' | 'center' | 'right'; + } + + interface PositionOptions { + top?: number; + right?: number; + bottom?: number; + left?: number; + } +} diff --git a/types/boxen/tsconfig.json b/types/boxen/tsconfig.json new file mode 100644 index 0000000000..6d34147e83 --- /dev/null +++ b/types/boxen/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", + "boxen-tests.ts" + ] +} diff --git a/types/boxen/tslint.json b/types/boxen/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/boxen/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ae36dd34749fc79a4cba7bd0e092f6c5495ca6ad Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Mon, 31 Dec 2018 13:50:31 -0500 Subject: [PATCH 090/208] [readable-stream] Add readable-stream@2.3.6 definition (#31805) --- types/readable-stream/index.d.ts | 266 ++++++++++++++++++ .../readable-stream/readable-stream-tests.ts | 50 ++++ types/readable-stream/tsconfig.json | 23 ++ types/readable-stream/tslint.json | 1 + 4 files changed, 340 insertions(+) create mode 100644 types/readable-stream/index.d.ts create mode 100644 types/readable-stream/readable-stream-tests.ts create mode 100644 types/readable-stream/tsconfig.json create mode 100644 types/readable-stream/tslint.json diff --git a/types/readable-stream/index.d.ts b/types/readable-stream/index.d.ts new file mode 100644 index 0000000000..b63e1bae9d --- /dev/null +++ b/types/readable-stream/index.d.ts @@ -0,0 +1,266 @@ +// Type definitions for readable-stream 2.3 +// Project: https://github.com/nodejs/readable-stream +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as events from "events"; +import * as stream from "stream"; +import * as SafeBuffer from "safe-buffer"; +import { NodeStringDecoder } from "string_decoder"; + +declare class _Readable extends stream.Readable { + // static ReadableState: _Readable.ReadableState; + _readableState: _Readable.ReadableState; + destroyed: boolean; + + constructor(options?: _Readable.ReadableOptions); + + destroy(err?: Error, callback?: (error: Error | null) => void): this; + _undestroy(): void; +} + +declare namespace _Readable { + // ==== BufferList ==== + interface Entry { + data: D; + next: Entry | null; + } + + interface BufferList { + head: Entry; + tail: Entry; + length: number; + + push(v: D): void; + unshift(v: D): void; + shift(): D; + clear(): void; + join(s: any): string; + concat(n: number): D; + } + + // ==== destroy ==== + interface Destroy { + destroy(this: Readable | Writable, error: Error | null, callback?: (error: Error | null) => void): Readable | Writable; + undestroy(this: Readable | Writable): void; + } + + // ==== _stream_duplex ==== + type DuplexOptions = ReadableOptions & WritableOptions & { + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + }; + + class Duplex extends Writable implements /*extends*/_Readable, stream.Duplex { + allowHalfOpen: boolean; + destroyed: boolean; + // Readable + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + _readableState: ReadableState; + + _read(size?: number): void; + read(size?: number): any; + setEncoding(enc: string): this; + resume(): this; + pause(): this; + isPaused(): boolean; + unpipe(dest?: NodeJS.WritableStream): this; + unshift(chunk: any): boolean; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(err: Error | null, callback: (error: Error | null) => void): void; + destroy(err?: Error, callback?: (error: Error | null) => void): this; + pipe(dest: S, pipeOpts?: { end?: boolean }): S; + addListener(ev: string | symbol, fn: (...args: any[]) => void): this; + on(ev: string | symbol, fn: (...args: any[]) => void): this; + + _undestroy(): void; + [Symbol.asyncIterator](): AsyncIterableIterator; + // end-Readable + + constructor(options?: DuplexOptions); + } + + // ==== _stream_passthrough ==== + class PassThrough extends Transform implements stream.PassThrough { + constructor(options?: TransformOptions); + + _transform(chunk: T, encoding: string | null | undefined, callback: (error: any, data: T) => void): void; + } + + // ==== _stream_readable ==== + interface ReadableStateOptions { + defaultEncoding?: string; + encoding?: string; + highWaterMark?: number; + objectMode?: boolean; + readableObjectMode?: boolean; + readableHighWaterMark?: number; + } + + interface ReadableState { + objectMode: boolean; + highWaterMark: number; + buffer: BufferList; + length: number; + pipes: any; // NodeJS.WritableStream | any[]; // TODO + pipesCount: number; + flowing: any; + ended: boolean; + endEmitted: boolean; + reading: boolean; + sync: boolean; + needReadable: boolean; + emittedReadable: boolean; + readableListening: boolean; + resumeScheduled: boolean; + destroyed: boolean; + awaitDrain: number; + defaultEncoding: string; + readingMore: boolean; + decoder: NodeStringDecoder | null; + encoding: string | null; + + // new (options: ReadableStateOptions, stream: _Readable): ReadableState; + } + + type ReadableOptions = ReadableStateOptions & { + read?(this: _Readable, size: number): void; + destroy?(this: _Readable, error: Error | null, callback: (error: Error | null) => void): void; + }; + + class Readable extends _Readable { + constructor(options?: ReadableOptions); + } + + // ==== _stream_transform ==== + type TransformOptions = DuplexOptions & { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: (error?: Error, data?: any) => void): void; + flush?(this: Transform, callback: (er: any, data: any) => void): void; + }; + + class Transform extends Duplex implements stream.Transform { + _transformState: { + afterTransform: (this: Transform, er: any, data: any) => void | boolean; + needTransform: boolean; + transforming: boolean; + writecb: ((err: any) => any) | null; + writechunk: any; // TODO + writeencoding: string | null; + }; + + constructor(options?: TransformOptions); + + _transform(chunk: any, encoding: string, callback: (error?: Error, data?: any) => void): void; + _flush(callback: (error?: Error, data?: any) => void): void; + } + + // ==== _stream_writable ==== + interface CorkedRequest { + next: any; + entry: any; + finish(): void; + } + + interface BufferRequest { + chunk: any; // TODO + encoding: string; + isBuf: boolean; + callback: (error?: Error | null) => void; + next: BufferRequest | null; + } + + interface WritableStateOptions { + decodeStrings?: boolean; + defaultEncoding?: string; + highWaterMark?: number; + objectMode?: boolean; + writableObjectMode?: boolean; + writableHighWaterMark?: number; + } + + interface WritableState { + buffer: BufferRequest[]; + objectMode: boolean; + highWaterMark: number; + finalCalled: boolean; + needDrain: boolean; + ending: boolean; + ended: boolean; + finished: boolean; + destroyed: boolean; + decodeStrings: boolean; + defaultEncoding: string; + length: number; + writing: boolean; + corked: number; + sync: boolean; + bufferProcessing: boolean; + writelen: number; + pendingcb: number; + prefinished: boolean; + errorEmitted: boolean; + bufferedRequestCount: number; + writecb: ((err?: Error | null) => void) | null; + onwrite: (er?: Error | null) => any; + bufferedRequest: BufferRequest | null; + lastBufferedRequest: BufferRequest | null; + corkedRequestsFree: CorkedRequest; + + // new (options: WritableStateOptions, stream: Writable): WritableState; + + getBuffer(): BufferRequest[]; + } + + type WritableOptions = WritableStateOptions & { + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunk: ArrayLike<{ chunk: any; encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + }; + + class Writable extends stream.Writable { + // static WritableState: WritableState; + // private static realHasInstance: (obj: any) => boolean; + destroyed: boolean; + _writableState: WritableState; + + constructor(options?: WritableOptions); + + destroy(error?: Error, callback?: (error?: Error | null) => void): this; + _undestroy(): void; + } + + class Stream extends _Readable { + constructor(options?: ReadableOptions); + } + + // if (process.env.READABLE_STREAM === 'disable' && Stream) + let NodeBaseExport: stream.Readable & { + Readable: stream.Readable; + Writable: stream.Writable; + Duplex: stream.Duplex; + Transform: stream.Transform; + PassThrough: stream.PassThrough; + Stream: stream; + }; +} + +export = _Readable; +export as namespace _Readable; diff --git a/types/readable-stream/readable-stream-tests.ts b/types/readable-stream/readable-stream-tests.ts new file mode 100644 index 0000000000..34cdc462d5 --- /dev/null +++ b/types/readable-stream/readable-stream-tests.ts @@ -0,0 +1,50 @@ +import stream = require("stream"); +import RStream = require("readable-stream"); + +function testTypes() { + const ANY: any = null; + const _readableOpts: stream.ReadableOptions = ANY as RStream.ReadableOptions; + const _writableOpts: stream.WritableOptions = ANY as RStream.WritableOptions; + const _transformOpts: stream.TransformOptions = ANY as RStream.TransformOptions; + const _duplexOpts: stream.DuplexOptions = ANY as RStream.DuplexOptions; + + const _readable: typeof stream.Readable = RStream.Readable; + const _writable: typeof stream.Writable = RStream.Writable; + const _transform: typeof stream.Transform = RStream.Transform; + const _duplex: typeof stream.Duplex = RStream.Duplex; +} + +function test() { + const rs: stream.Stream = (null as any) as RStream.Stream; + const RS_Readable = RStream; + const RS_Writable = RStream.Writable; + const RS_Transform = RStream.Transform; + const RS_Duplex = RStream.Duplex; + + const streamR = new RS_Readable({ + objectMode: true, + read(size) { }, + destroy(error, cb) { } + }); + + streamR.once("end", () => { + process.nextTick(() => { + streamR.emit("close"); + }); + }); + + const row = null; + const i = 0; + if (streamR.push(row)) streamR.emit("result", row, i); + else streamR.emit('error', new Error("a possible exception")); // Pass on any errors + streamR.push(null); // pushing null, indicating EOF + + const streamW = new RS_Writable({ + write(chunk, enc, cb) { }, + writev(chunks, cb) { }, + destroy(error, cb) { }, + final(cb) { } + }); + streamW.write(new Buffer("test")); + streamW.emit("finish"); +} diff --git a/types/readable-stream/tsconfig.json b/types/readable-stream/tsconfig.json new file mode 100644 index 0000000000..0c769a8761 --- /dev/null +++ b/types/readable-stream/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", + "readable-stream-tests.ts" + ] +} \ No newline at end of file diff --git a/types/readable-stream/tslint.json b/types/readable-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/readable-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6fd150e9519e24402e5ffd937d8c8a1da3d4f87e Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 31 Dec 2018 18:51:27 +0000 Subject: [PATCH 091/208] [@keyv/mongo] Add types (#31806) --- types/keyv__mongo/index.d.ts | 33 ++++++++++++++++++++++++++ types/keyv__mongo/keyv__mongo-tests.ts | 12 ++++++++++ types/keyv__mongo/tsconfig.json | 28 ++++++++++++++++++++++ types/keyv__mongo/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100644 types/keyv__mongo/index.d.ts create mode 100644 types/keyv__mongo/keyv__mongo-tests.ts create mode 100644 types/keyv__mongo/tsconfig.json create mode 100644 types/keyv__mongo/tslint.json diff --git a/types/keyv__mongo/index.d.ts b/types/keyv__mongo/index.d.ts new file mode 100644 index 0000000000..f468f3530b --- /dev/null +++ b/types/keyv__mongo/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for @keyv/mongo 1.0 +// Project: https://github.com/lukechilds/keyv-mongo +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { EventEmitter } from 'events'; + +export = KeyvMongo; + +declare class KeyvMongo extends EventEmitter implements Store { + readonly ttlSupport: false; + namespace?: string; + + constructor(uri?: string); + constructor(options?: KeyvMongo.Options); // tslint:disable-line:unified-signatures + + get(key: string): Promise; + set(key: string, value: TValue, ttl?: number): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvMongo { + interface Options { + uri?: string; + url?: string; + collection?: string; + } +} diff --git a/types/keyv__mongo/keyv__mongo-tests.ts b/types/keyv__mongo/keyv__mongo-tests.ts new file mode 100644 index 0000000000..6e8d1ea971 --- /dev/null +++ b/types/keyv__mongo/keyv__mongo-tests.ts @@ -0,0 +1,12 @@ +import Keyv = require('keyv'); +import KeyvMongo = require('@keyv/mongo'); + +new Keyv('mongodb://user:pass@localhost:27017/dbname', { collection: 'cache' }); + +new KeyvMongo({ uri: 'mongodb://user:pass@localhost:27017/dbname' }); +new KeyvMongo({ url: 'mongodb://user:pass@localhost:27017/dbname' }); +new KeyvMongo({ collection: 'cache' }); +new KeyvMongo('mongodb://user:pass@localhost:27017/dbname'); + +const mongo = new KeyvMongo('mongodb://user:pass@localhost:27017/dbname'); +new Keyv({ store: mongo }); diff --git a/types/keyv__mongo/tsconfig.json b/types/keyv__mongo/tsconfig.json new file mode 100644 index 0000000000..ca38c4e787 --- /dev/null +++ b/types/keyv__mongo/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/mongo": [ + "keyv__mongo" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__mongo-tests.ts" + ] +} diff --git a/types/keyv__mongo/tslint.json b/types/keyv__mongo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__mongo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 56f95b35268b7a183d8e8bbd0934568d5f6369f3 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 31 Dec 2018 18:53:51 +0000 Subject: [PATCH 092/208] [@keyv/postgres] Add types (#31808) --- types/keyv__postgres/index.d.ts | 32 ++++++++++++++++++++ types/keyv__postgres/keyv__postgres-tests.ts | 11 +++++++ types/keyv__postgres/tsconfig.json | 28 +++++++++++++++++ types/keyv__postgres/tslint.json | 1 + 4 files changed, 72 insertions(+) create mode 100644 types/keyv__postgres/index.d.ts create mode 100644 types/keyv__postgres/keyv__postgres-tests.ts create mode 100644 types/keyv__postgres/tsconfig.json create mode 100644 types/keyv__postgres/tslint.json diff --git a/types/keyv__postgres/index.d.ts b/types/keyv__postgres/index.d.ts new file mode 100644 index 0000000000..3431ce748f --- /dev/null +++ b/types/keyv__postgres/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for @keyv/postgres 1.0 +// Project: https://github.com/lukechilds/keyv-postgres +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { EventEmitter } from 'events'; + +export = KeyvPostgres; + +declare class KeyvPostgres extends EventEmitter implements Store { + readonly ttlSupport: false; + namespace?: string; + + constructor(options?: KeyvPostgres.Options); + + get(key: string): Promise; + set(key: string, value: string | undefined): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvPostgres { + interface Options { + uri?: string; + table?: string; + keySize?: number; + } +} diff --git a/types/keyv__postgres/keyv__postgres-tests.ts b/types/keyv__postgres/keyv__postgres-tests.ts new file mode 100644 index 0000000000..1ad3d362d0 --- /dev/null +++ b/types/keyv__postgres/keyv__postgres-tests.ts @@ -0,0 +1,11 @@ +import Keyv = require('keyv'); +import KeyvPostgres = require('@keyv/postgres'); + +new Keyv('postgresql://user:pass@localhost:5432/dbname', { table: 'cache' }); + +new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); +new KeyvPostgres({ table: 'cache' }); +new KeyvPostgres({ keySize: 100 }); + +const postgres = new KeyvPostgres({ uri: 'postgresql://user:pass@localhost:5432/dbname' }); +new Keyv({ store: postgres }); diff --git a/types/keyv__postgres/tsconfig.json b/types/keyv__postgres/tsconfig.json new file mode 100644 index 0000000000..d793c92899 --- /dev/null +++ b/types/keyv__postgres/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/postgres": [ + "keyv__postgres" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__postgres-tests.ts" + ] +} diff --git a/types/keyv__postgres/tslint.json b/types/keyv__postgres/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__postgres/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 8492d9a89b54d4eec3167e75c5b04a27e985b435 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 31 Dec 2018 18:55:20 +0000 Subject: [PATCH 093/208] [@keyv/redis] Add types (#31809) --- types/keyv__redis/index.d.ts | 32 ++++++++++++++++++++++++++ types/keyv__redis/keyv__redis-tests.ts | 13 +++++++++++ types/keyv__redis/tsconfig.json | 28 ++++++++++++++++++++++ types/keyv__redis/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100644 types/keyv__redis/index.d.ts create mode 100644 types/keyv__redis/keyv__redis-tests.ts create mode 100644 types/keyv__redis/tsconfig.json create mode 100644 types/keyv__redis/tslint.json diff --git a/types/keyv__redis/index.d.ts b/types/keyv__redis/index.d.ts new file mode 100644 index 0000000000..bf009906f8 --- /dev/null +++ b/types/keyv__redis/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for @keyv/redis 1.3 +// Project: https://github.com/lukechilds/keyv-redis +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { ClientOpts } from 'redis'; +import { EventEmitter } from 'events'; + +export = KeyvRedis; + +declare class KeyvRedis extends EventEmitter implements Store { + readonly ttlSupport: true; + namespace?: string; + + constructor(options?: KeyvRedis.Options); + constructor(uri: string, options?: KeyvRedis.Options); + + get(key: string): Promise; + set(key: string, value: string | undefined, ttl?: number): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvRedis { + interface Options extends ClientOpts { + uri?: string; + } +} diff --git a/types/keyv__redis/keyv__redis-tests.ts b/types/keyv__redis/keyv__redis-tests.ts new file mode 100644 index 0000000000..3f0187fd38 --- /dev/null +++ b/types/keyv__redis/keyv__redis-tests.ts @@ -0,0 +1,13 @@ +import Keyv = require('keyv'); +import KeyvRedis = require('@keyv/redis'); + +new Keyv('redis://user:pass@localhost:6379', { max_attempts: 1 }); + +new KeyvRedis({ uri: 'redis://user:pass@localhost:6379' }); +new KeyvRedis('redis://user:pass@localhost:6379', { max_attempts: 1 }); +new KeyvRedis('redis://user:pass@localhost:6379', { + uri: 'redis://user:pass@localhost:6379', + max_attempts: 1, +}); +const redis = new KeyvRedis('redis://user:pass@localhost:6379'); +new Keyv({ store: redis }); diff --git a/types/keyv__redis/tsconfig.json b/types/keyv__redis/tsconfig.json new file mode 100644 index 0000000000..bbd87dfade --- /dev/null +++ b/types/keyv__redis/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/redis": [ + "keyv__redis" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__redis-tests.ts" + ] +} diff --git a/types/keyv__redis/tslint.json b/types/keyv__redis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__redis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From a1a6a819749f84dc1d400ff7150fc851b170ba52 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 31 Dec 2018 19:04:17 +0000 Subject: [PATCH 094/208] [typpy] Add types (#31804) --- types/typpy/index.d.ts | 68 ++++++++++++++++++++++++++++++ types/typpy/tsconfig.json | 23 +++++++++++ types/typpy/tslint.json | 1 + types/typpy/typpy-tests.ts | 84 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+) create mode 100644 types/typpy/index.d.ts create mode 100644 types/typpy/tsconfig.json create mode 100644 types/typpy/tslint.json create mode 100644 types/typpy/typpy-tests.ts diff --git a/types/typpy/index.d.ts b/types/typpy/index.d.ts new file mode 100644 index 0000000000..29ee39d881 --- /dev/null +++ b/types/typpy/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for typpy 2.3 +// Project: https://github.com/IonicaBizau/typpy +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = Typpy; + +declare const Typpy: Typpy.TyppyFn; + +declare namespace Typpy { + type TyppyFn = IsFn & + CompareFn & { + is: CompareFn; + get: GetFn; + }; + + interface IsFn { + (input?: undefined): 'undefined'; + (input: null): 'null'; + (input: string): 'string'; + (input: boolean): 'boolean'; + (input: any[]): 'array'; + (input: RegExp): 'regexp'; + (input: Function): 'function'; // tslint:disable-line:ban-types + (input: number): 'number' | 'nan'; + (input: any): string; + } + + interface CompareFn { + (input: undefined, compareTo: 'undefined' | undefined): true; + (input: null, compareTo: 'null' | null): true; + (input: string, compareTo: 'string' | StringConstructor): true; + (input: boolean, compareTo: 'boolean' | BooleanConstructor): true; + (input: any[], compareTo: 'array' | ArrayConstructor): true; + (input: RegExp, compareTo: 'regexp' | RegExpConstructor): true; + (input: Function, compareTo: 'function' | FunctionConstructor): true; // tslint:disable-line:ban-types + (input: number, compareTo: 'number' | 'nan' | NumberConstructor | number): boolean; + (input: object, compareTo: 'object' | ObjectConstructor): boolean; + (input: any, compareTo: any): boolean; + } + + interface GetFn { + (input?: undefined, asString?: false): void; + (input: null, asString?: false): null; + (input: string, asString?: false): StringConstructor; + (input: number, asString?: false): NumberConstructor | number; + (input: boolean, asString?: false): BooleanConstructor; + (input: any[], asString?: false): ArrayConstructor; + (input: RegExp, asString?: false): RegExpConstructor; + (input: Function, asString?: false): FunctionConstructor; // tslint:disable-line:ban-types + (input: any, asString?: false): ConstructorFn; + + (input: undefined, asString: true): 'undefined'; + (input: null, asString: true): 'null'; + (input: string, asString: true): 'string'; + (input: number, asString: true): 'number' | 'nan'; + (input: boolean, asString: true): 'boolean'; + (input: any[], asString: true): 'array'; + (input: RegExp, asString: true): 'regexp'; + (input: Function, asString: true): 'function'; // tslint:disable-line:ban-types + (input: any, asString: true): string; + } + + interface ConstructorFn { + new (...args: any[]): any; + } +} diff --git a/types/typpy/tsconfig.json b/types/typpy/tsconfig.json new file mode 100644 index 0000000000..bce836aa9b --- /dev/null +++ b/types/typpy/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", + "typpy-tests.ts" + ] +} diff --git a/types/typpy/tslint.json b/types/typpy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/typpy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/typpy/typpy-tests.ts b/types/typpy/typpy-tests.ts new file mode 100644 index 0000000000..f5f79aa413 --- /dev/null +++ b/types/typpy/typpy-tests.ts @@ -0,0 +1,84 @@ +import Typpy = require('typpy'); + +Typpy(); // $ExpectType "undefined" +Typpy(undefined); // $ExpectType "undefined" +Typpy(null); // $ExpectType "null" +Typpy(''); // $ExpectType "string" +Typpy(true); // $ExpectType "boolean" +Typpy([]); // $ExpectType "array" +Typpy(/./); // $ExpectType "regexp" +Typpy(() => {}); // $ExpectType "function" +Typpy(1); // $ExpectType "number" | "nan" +Typpy({}); // $ExpectType string + +Typpy(undefined, undefined); // $ExpectType true +Typpy(undefined, 'undefined'); // $ExpectType true +Typpy(null, null); // $ExpectType true +Typpy(null, 'null'); // $ExpectType true +Typpy('', String); // $ExpectType true +Typpy('', 'string'); // $ExpectType true +Typpy(true, Boolean); // $ExpectType true +Typpy(true, 'boolean'); // $ExpectType true +Typpy([], Array); // $ExpectType true +Typpy([], 'array'); // $ExpectType true +Typpy(/./, RegExp); // $ExpectType true +Typpy(/./, 'regexp'); // $ExpectType true +Typpy(() => {}, Function); // $ExpectType true +Typpy(() => {}, 'function'); // $ExpectType true +Typpy(1, Number); // $ExpectType boolean +Typpy(1, NaN); // $ExpectType boolean +Typpy(1, 1); // $ExpectType boolean +Typpy({}, Object); // $ExpectType boolean +Typpy({}, 'object'); // $ExpectType boolean +Typpy({}, true); // $ExpectType boolean + +Typpy.is(undefined, undefined); // $ExpectType true +Typpy.is(undefined, 'undefined'); // $ExpectType true +Typpy.is(null, null); // $ExpectType true +Typpy.is(null, 'null'); // $ExpectType true +Typpy.is('', String); // $ExpectType true +Typpy.is('', 'string'); // $ExpectType true +Typpy.is(true, Boolean); // $ExpectType true +Typpy.is(true, 'boolean'); // $ExpectType true +Typpy.is([], Array); // $ExpectType true +Typpy.is([], 'array'); // $ExpectType true +Typpy.is(/./, RegExp); // $ExpectType true +Typpy.is(/./, 'regexp'); // $ExpectType true +Typpy.is(() => {}, Function); // $ExpectType true +Typpy.is(() => {}, 'function'); // $ExpectType true +Typpy.is(1, Number); // $ExpectType boolean +Typpy.is(1, NaN); // $ExpectType boolean +Typpy.is(1, 1); // $ExpectType boolean +Typpy.is({}, Object); // $ExpectType boolean +Typpy.is({}, 'object'); // $ExpectType boolean +Typpy.is({}, true); // $ExpectType boolean + +Typpy.get(); // $ExpectType void +Typpy.get(undefined); // $ExpectType void +Typpy.get(null); // $ExpectType null +Typpy.get(''); // $ExpectType StringConstructor +Typpy.get(true); // $ExpectType BooleanConstructor +Typpy.get([]); // $ExpectType ArrayConstructor +Typpy.get(/./); // $ExpectType RegExpConstructor +Typpy.get(() => {}); // $ExpectType FunctionConstructor +Typpy.get(1); // $ExpectType number | NumberConstructor +Typpy.get({}); // $ExpectType ConstructorFn +Typpy.get(undefined, false); // $ExpectType void +Typpy.get(null, false); // $ExpectType null +Typpy.get('', false); // $ExpectType StringConstructor +Typpy.get(true, false); // $ExpectType BooleanConstructor +Typpy.get([], false); // $ExpectType ArrayConstructor +Typpy.get(/./, false); // $ExpectType RegExpConstructor +Typpy.get(() => {}, false); // $ExpectType FunctionConstructor +Typpy.get(1, false); // $ExpectType number | NumberConstructor +Typpy.get({}, false); // $ExpectType ConstructorFn + +Typpy.get(undefined, true); // $ExpectType "undefined" +Typpy.get(null, true); // $ExpectType "null" +Typpy.get('', true); // $ExpectType "string" +Typpy.get(true, true); // $ExpectType "boolean" +Typpy.get([], true); // $ExpectType "array" +Typpy.get(/./, true); // $ExpectType "regexp" +Typpy.get(() => {}, true); // $ExpectType "function" +Typpy.get(1, true); // $ExpectType "number" | "nan" +Typpy.get({}, true); // $ExpectType string From d9068c9d4e85c4ff5d0df1c8ee76da4236decc0d Mon Sep 17 00:00:00 2001 From: Alex Jerabek <38896772+AlexJerabek@users.noreply.github.com> Date: Mon, 31 Dec 2018 11:31:10 -0800 Subject: [PATCH 095/208] Correcting RangeFill description (#31815) --- types/office-js-preview/index.d.ts | 10 +++++----- types/office-js/index.d.ts | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 4d41651189..2803e305ff 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -23890,7 +23890,7 @@ declare namespace Excel { context: RequestContext; /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -27767,7 +27767,7 @@ declare namespace Excel { * * [Api set: ExcelApi 1.1] * - * @param color HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * @param color HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). */ setSolidColor(color: string): void; /** @@ -42837,7 +42837,7 @@ declare namespace Excel { interface RangeFillUpdateData { /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -47921,7 +47921,7 @@ declare namespace Excel { interface RangeFillData { /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -54273,7 +54273,7 @@ declare namespace Excel { $all?: boolean; /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index c59c277872..4c451e9de6 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -22142,7 +22142,7 @@ declare namespace Excel { class RangeFill extends OfficeExtension.ClientObject { /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -25212,7 +25212,7 @@ declare namespace Excel { * * [Api set: ExcelApi 1.1] * - * @param color HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). + * @param color HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). */ setSolidColor(color: string): void; toJSON(): { @@ -36109,7 +36109,7 @@ declare namespace Excel { interface RangeFillUpdateData { /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -39754,7 +39754,7 @@ declare namespace Excel { interface RangeFillData { /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ @@ -44347,7 +44347,7 @@ declare namespace Excel { $all?: boolean; /** * - * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") + * HTML color code representing the color of the background, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") * * [Api set: ExcelApi 1.1] */ From bc5ffa8aa7f5ed649c230d8178dc6682dfd9f2de Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 30 Dec 2018 00:45:40 +0100 Subject: [PATCH 096/208] [sparse-bitfield] Add types --- types/sparse-bitfield/index.d.ts | 74 +++++++++++++++++++ .../sparse-bitfield/sparse-bitfield-tests.ts | 24 ++++++ types/sparse-bitfield/tsconfig.json | 23 ++++++ types/sparse-bitfield/tslint.json | 1 + 4 files changed, 122 insertions(+) create mode 100644 types/sparse-bitfield/index.d.ts create mode 100644 types/sparse-bitfield/sparse-bitfield-tests.ts create mode 100644 types/sparse-bitfield/tsconfig.json create mode 100644 types/sparse-bitfield/tslint.json diff --git a/types/sparse-bitfield/index.d.ts b/types/sparse-bitfield/index.d.ts new file mode 100644 index 0000000000..fb1c670ab0 --- /dev/null +++ b/types/sparse-bitfield/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for sparse-bitfield 3.0 +// Project: https://github.com/mafintosh/sparse-bitfield +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { PagerInstance } from 'memory-pager'; + +export = BitField; + +declare const BitField: BitField; + +interface BitField { + (bufferOrOptions?: BitField.Options | Buffer): BitField.BitFieldInstance; + new (bufferOrOptions?: BitField.Options | Buffer): BitField.BitFieldInstance; +} + +declare namespace BitField { + interface Options { + /** + * @default 0 + */ + pageOffset?: number; + /** + * How big should the partial buffers be. + * @default 1024 + */ + pageSize?: number; + /** + * A pre-configured Pager instance. + */ + pages?: PagerInstance; + /** + * An existing bitfield. + */ + buffer?: Buffer; + /** + * Track when pages are being updated in the pager. + * @default false + */ + trackUpdates?: boolean; + } + + interface BitFieldInstance { + /** + * A `memory-pager` instance that is managing the underlying memory. + * If you set `trackUpdates` to `true` in the constructor you can use `.lastUpdate()` on this instance + * to get the last updated memory page. + */ + readonly pages: PagerInstance; + + /** + * Get the value of a bit. + */ + get(index: number): boolean; + /** + * Get the value of a byte. + */ + getByte(index: number): number; + /** + * Set a bit to true or false. + */ + set(index: number, value: boolean): boolean; + /** + * Set a byte to a new value. + */ + setByte(index: number, byte: number): boolean; + /** + * Get a single buffer representing the entire bitfield. + */ + toBuffer(): Buffer; + } +} diff --git a/types/sparse-bitfield/sparse-bitfield-tests.ts b/types/sparse-bitfield/sparse-bitfield-tests.ts new file mode 100644 index 0000000000..0687c53336 --- /dev/null +++ b/types/sparse-bitfield/sparse-bitfield-tests.ts @@ -0,0 +1,24 @@ +import BitField = require('sparse-bitfield'); +import Pager = require('memory-pager'); + +const bits = BitField(); +BitField(new Buffer(1)); +BitField({ pageOffset: 1 }); +BitField({ pageSize: 1024 }); +BitField({ pages: new Pager() }); +BitField({ buffer: new Buffer(1) }); +BitField({ trackUpdates: true }); +new BitField(); +new BitField(new Buffer(1)); +new BitField({ pageOffset: 1 }); +new BitField({ pageSize: 1024 }); +new BitField({ pages: new Pager() }); +new BitField({ buffer: new Buffer(1) }); +new BitField({ trackUpdates: true }); + +bits.get(0); // $ExpectType boolean +bits.getByte(0); // $ExpectType number +bits.set(0, true); // $ExpectType boolean +bits.setByte(0, 1); // $ExpectType boolean +bits.toBuffer(); // $ExpectType Buffer +bits.pages; // $ExpectType PagerInstance diff --git a/types/sparse-bitfield/tsconfig.json b/types/sparse-bitfield/tsconfig.json new file mode 100644 index 0000000000..8be85b6832 --- /dev/null +++ b/types/sparse-bitfield/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", + "sparse-bitfield-tests.ts" + ] +} diff --git a/types/sparse-bitfield/tslint.json b/types/sparse-bitfield/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sparse-bitfield/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 71211f88c46a7af6a6734117507c5a0405fb7ef4 Mon Sep 17 00:00:00 2001 From: Rene Haas Date: Mon, 31 Dec 2018 21:52:49 +0100 Subject: [PATCH 097/208] OverlayScrollbars TypeScript definitions (#31784) * OverlayScrollbars TypeScript definitions * added missing tests and improved definitions --- types/overlayscrollbars/index.d.ts | 376 ++++++++++++++++++ .../overlayscrollbars-tests.ts | 41 ++ types/overlayscrollbars/tsconfig.json | 24 ++ types/overlayscrollbars/tslint.json | 3 + 4 files changed, 444 insertions(+) create mode 100644 types/overlayscrollbars/index.d.ts create mode 100644 types/overlayscrollbars/overlayscrollbars-tests.ts create mode 100644 types/overlayscrollbars/tsconfig.json create mode 100644 types/overlayscrollbars/tslint.json diff --git a/types/overlayscrollbars/index.d.ts b/types/overlayscrollbars/index.d.ts new file mode 100644 index 0000000000..6b1bee189a --- /dev/null +++ b/types/overlayscrollbars/index.d.ts @@ -0,0 +1,376 @@ +// Type definitions for OverlayScrollbars 1.6 +// Project: https://kingsora.github.io/OverlayScrollbars +// Definitions by: KingSora +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace OverlayScrollbars { + type ResizeBehavior = "none" | "both" | "horizontal" | "vertical" | "n" | "b" | "h" | "v"; + + type OverflowBehavior = "hidden" | "scroll" | "visible-hidden" | "visible-scroll" | "h" | "s" | "v-h" | "v-s"; + + type VisibilityBehavior = "visible" | "hidden" | "auto" | "v" | "h" | "a"; + + type AutoHideBehavior = "never" | "scroll" | "leave" | "move" | "n" | "s" | "l" | "m"; + + type ScrollBehavior = "always" | "ifneeded" | "never"; + + type BlockBehavior = "begin" | "end" | "center" | "nearest"; + + type Easing = string | null | undefined; + + type Margin = number | boolean; + + type Position = number | string; + + type BasicEventCallback = (this: OverlayScrollbars) => void; + + type ScrollEventCallback = (this: OverlayScrollbars, args?: UIEvent) => void; + + type OverflowChangedCallback = (this: OverlayScrollbars, args?: OverflowChangedArgs) => void; + + type OverflowAmountChangedCallback = (this: OverlayScrollbars, args?: OverflowAmountChangedArgs) => void; + + type DirectionChangedCallback = (this: OverlayScrollbars, args?: DirectionChangedArgs) => void; + + type SizeChangedCallback = (this: OverlayScrollbars, args?: SizeChangedArgs) => void; + + type UpdatedCallback = (this: OverlayScrollbars, args?: UpdatedArgs) => void; + + type Coordinates = { x?: Position; y?: Position } + | { l?: Position; t?: Position } + | { left?: Position; top?: Position } + | [Position, Position] + | Position + | HTMLElement + | JQuery + | { + el: HTMLElement | JQuery; + scroll?: ScrollBehavior | { x?: ScrollBehavior; y?: ScrollBehavior } | [ScrollBehavior, ScrollBehavior]; + block?: BlockBehavior | { x?: BlockBehavior; y?: BlockBehavior } | [BlockBehavior, BlockBehavior]; + margin?: Margin + | { + top?: Margin; + right?: Margin; + bottom?: Margin; + left?: Margin; + } + | [Margin, Margin] + | [Margin, Margin, Margin, Margin]; + }; + + interface OverflowChangedArgs { + x: boolean; + y: boolean; + xScrollable: boolean; + yScrollable: boolean; + clipped: boolean; + } + + interface OverflowAmountChangedArgs { + x: number; + y: number; + } + + interface DirectionChangedArgs { + isRTL: number; + dir: string; + } + + interface SizeChangedArgs { + width: number; + height: number; + } + + interface UpdatedArgs { + forced: boolean; + } + + interface Options { + className?: string | null; + resize?: ResizeBehavior; + sizeAutoCapable?: boolean; + clipAlways?: boolean; + normalizeRTL?: boolean; + paddingAbsolute?: boolean; + autoUpdate?: boolean | null; + autoUpdateInterval?: number; + nativeScrollbarsOverlaid?: { + showNativeScrollbars?: boolean; + initialize?: boolean; + }; + overflowBehavior?: { + x?: OverflowBehavior; + y?: OverflowBehavior; + }; + scrollbars?: { + visibility?: VisibilityBehavior; + autoHide?: AutoHideBehavior; + autoHideDelay?: number; + dragScrolling?: boolean; + clickScrolling?: boolean; + touchSupport?: boolean; + }; + textarea?: { + dynWidth?: boolean; + dynHeight?: boolean; + inheritedAttrs?: string | ReadonlyArray | null; + }; + callbacks?: { + onInitialized?: BasicEventCallback | null; + onInitializationWithdrawn?: BasicEventCallback | null; + onDestroyed?: BasicEventCallback | null; + onScrollStart?: ScrollEventCallback | null; + onScroll?: ScrollEventCallback | null; + onScrollStop?: ScrollEventCallback | null; + onOverflowChanged?: OverflowChangedCallback | null; + onOverflowAmountChanged?: OverflowAmountChangedCallback | null; + onDirectionChanged?: DirectionChangedCallback | null; + onContentSizeChanged?: SizeChangedCallback | null; + onHostSizeChanged?: SizeChangedCallback | null; + onUpdated?: UpdatedCallback | null; + }; + } + + interface ScrollInfo { + position: { + x: number; + y: number; + }; + ratio: { + x: number; + y: number; + }; + max: { + x: number; + y: number; + }; + handleOffset: { + x: number; + y: number; + }; + handleLength: { + x: number; + y: number; + }; + handleLengthRatio: { + x: number; + y: number; + }; + trackLength: { + x: number; + y: number; + }; + isRTL: boolean; + isRTLNormalized: boolean; + } + + interface Elements { + target: HTMLElement; + host: HTMLElement; + padding: HTMLElement; + viewport: HTMLElement; + content: HTMLElement; + scrollbarHorizontal: { + scrollbar: HTMLElement; + track: HTMLElement; + handle: HTMLElement; + }; + scrollbarVertical: { + scrollbar: HTMLElement; + track: HTMLElement; + handle: HTMLElement; + }; + scrollbarCorner: HTMLElement; + } + + interface State { + sleeping: boolean; + autoUpdate: boolean; + widthAuto: boolean; + heightAuto: boolean; + documentMixed: boolean; + padding: { + t: number; + r: number; + b: number; + l: number; + }; + overflowAmount: { + x: number; + y: number; + }; + hideOverflow: { + x: boolean; + y: boolean; + xs: boolean; + ys: boolean; + }; + hasOverflow: { + x: boolean; + y: boolean; + }; + contentScrollSize: { + width: number; + height: number; + }; + viewportSize: { + width: number; + height: number; + }; + hostSize: { + width: number; + height: number; + }; + } + + interface Extension { + contract(global: any): boolean; + + added(options?: {}): void; + + removed(): void; + + on(callbackName: string, callbackArgs?: UIEvent | OverflowChangedArgs | OverflowAmountChangedArgs | DirectionChangedArgs | SizeChangedArgs | UpdatedArgs): void; + } + + interface ExtensionInfo { + name: string; + extensionFactory: (this: OverlayScrollbars, defaultOptions: {}, compatibility: Compatibility, framework: any) => Extension; + defaultOptions?: {}; + } + + interface Globals { + defaultOptions: {}; + autoUpdateLoop: boolean; + autoUpdateRecommended: boolean; + supportMutationObserver: boolean; + supportResizeObserver: boolean; + supportPassiveEvents: boolean; + supportTransform: boolean; + supportTransition: boolean; + restrictedMeasuring: boolean; + nativeScrollbarStyling: boolean; + cssCalc: string | null; + nativeScrollbarSize: { + x: number; + y: number; + }; + nativeScrollbarIsOverlaid: { + x: boolean; + y: boolean; + }; + overlayScrollbarDummySize: { + x: number; + y: number; + }; + rtlScrollBehavior: { + i: boolean; + n: boolean; + }; + } + + interface Compatibility { + wW(): number; + wH(): number; + mO(): any; + rO(): any; + rAF(): (callback: (...args: any[]) => any) => number; + cAF(): (requestID: number) => void; + now(): number; + stpP(event: Event): void; + prvD(event: Event): void; + page(event: MouseEvent): { x: number, y: number }; + mBtn(event: MouseEvent): number; + inA(item: T, array: T[]): number; + isA(obj: any): boolean; + type(obj: any): string; + bind(func: (...args: any[]) => any, thisObj: any, ... args: any[]): any; + } +} + +interface OverlayScrollbars { + options(): OverlayScrollbars.Options; + options(options: OverlayScrollbars.Options): void; + options(optionName: string): any; + options(optionName: string, optionValue: {} | null): void; + + update(force?: boolean): void; + + sleep(): void; + + scroll(): OverlayScrollbars.ScrollInfo; + scroll( + coordinates: OverlayScrollbars.Coordinates, + duration?: number, + easing?: OverlayScrollbars.Easing | { x?: OverlayScrollbars.Easing; y?: OverlayScrollbars.Easing } | [OverlayScrollbars.Easing, OverlayScrollbars.Easing], + complete?: (...args: any[]) => any + ): void; + scroll(coordinates: OverlayScrollbars.Coordinates, options: {}): void; + + scrollStop(): OverlayScrollbars; + + getElements(): OverlayScrollbars.Elements; + getElements(elementName: string): any; + + getState(): OverlayScrollbars.State; + getState(stateProperty: string): any; + + destroy(): void; + + ext(): {}; + ext(extensionName: string): OverlayScrollbars.Extension; + + addExt(extensionName: string, options: {}): OverlayScrollbars.Extension; + + removeExt(extensionName: string): boolean; +} + +interface OverlayScrollbarsStatic { + ( + element: HTMLElement | Element | JQuery, + options: OverlayScrollbars.Options, + extensions?: string | ReadonlyArray | { [extensionName: string]: {} } + ): OverlayScrollbars; + ( + element: HTMLElement | Element | JQuery | null + ): OverlayScrollbars | undefined; + + ( + elements: NodeListOf | ReadonlyArray | JQuery, + options: OverlayScrollbars.Options, + extensions?: string | ReadonlyArray | { [extensionName: string]: {} } + ): OverlayScrollbars | OverlayScrollbars[] | undefined; + ( + elements: NodeListOf | ReadonlyArray | JQuery, + filter?: string | ((element: Element, instance: OverlayScrollbars) => boolean) + ): OverlayScrollbars | OverlayScrollbars[] | undefined; + + globals(): OverlayScrollbars.Globals; + + defaultOptions(): OverlayScrollbars.Options; + defaultOptions(newDefaultOptions: OverlayScrollbars.Options): void; + + extension(): { [index: number]: OverlayScrollbars.ExtensionInfo; length: number }; + extension(extensionName: string): OverlayScrollbars.ExtensionInfo; + extension( + extensionName: string, + extensionFactory: (this: OverlayScrollbars, defaultOptions: {}, + compatibility: OverlayScrollbars.Compatibility, framework: any) => OverlayScrollbars.Extension, + defaultOptions?: {} + ): void; + extension(extensionName: string, extensionFactory: null | undefined): void; +} + +interface JQuery { + overlayScrollbars( + options: OverlayScrollbars.Options, + extensions?: string | ReadonlyArray | { [extensionName: string]: {} } + ): JQuery; + overlayScrollbars( + filter?: string | ((element: Element, instance: OverlayScrollbars) => boolean) + ): OverlayScrollbars | OverlayScrollbars[] | undefined; +} + +export as namespace OverlayScrollbars; +export = OverlayScrollbars; +declare const OverlayScrollbars: OverlayScrollbarsStatic; diff --git a/types/overlayscrollbars/overlayscrollbars-tests.ts b/types/overlayscrollbars/overlayscrollbars-tests.ts new file mode 100644 index 0000000000..2430a91fe3 --- /dev/null +++ b/types/overlayscrollbars/overlayscrollbars-tests.ts @@ -0,0 +1,41 @@ +function test_init() { + // body is guaranteed a single element + const osInstanceBody: OverlayScrollbars = OverlayScrollbars(document.body, { }); + + // elementById is a single element or null + const elementById: HTMLElement | null = document.getElementById('os'); + if (elementById != null) { + // OverlayScrollbars can't be initialized with null as element + const osInstanceId: OverlayScrollbars = OverlayScrollbars(elementById, { }); + } + + // elementsQuerySelector can be a empty-array, a single-item-array or a multi-item-array + const elementsQuerySelector: NodeListOf = document.querySelectorAll('.os'); + if (elementsQuerySelector.length > 0) { + // its up to the user to cast the result properly + if (elementsQuerySelector.length === 1) { + const osInstance: OverlayScrollbars = OverlayScrollbars(elementsQuerySelector, { }); + } else { + const osInstances: OverlayScrollbars[] = OverlayScrollbars(elementsQuerySelector, { }); + } + } +} + +function test_getInstance() { + // body is guaranteed a single element, but the plugin might not be initialized to it + const osInstanceBody: OverlayScrollbars | undefined = OverlayScrollbars(document.body); + + // elementById is a single element or null, but the plugin might not be initialized to it if not null + const osInstanceId: OverlayScrollbars | undefined = OverlayScrollbars(document.getElementById('os')); + + // elementsQuerySelector can be a empty-array, a single-item-array or a multi-item-array + const elementsQuerySelector: NodeListOf = document.querySelectorAll('.os'); + if (elementsQuerySelector.length > 0) { + // its up to the user to cast the result properly + if (elementsQuerySelector.length === 1) { + const osInstance: OverlayScrollbars = OverlayScrollbars(elementsQuerySelector); + } else { + const osInstances: OverlayScrollbars[] = OverlayScrollbars(elementsQuerySelector); + } + } +} diff --git a/types/overlayscrollbars/tsconfig.json b/types/overlayscrollbars/tsconfig.json new file mode 100644 index 0000000000..30a4a809b1 --- /dev/null +++ b/types/overlayscrollbars/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", + "overlayscrollbars-tests.ts" + ] +} diff --git a/types/overlayscrollbars/tslint.json b/types/overlayscrollbars/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/overlayscrollbars/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From e338aaeaa4fd51bceb9e49a66b9b51d579e4ab02 Mon Sep 17 00:00:00 2001 From: Claudio Procida Date: Mon, 31 Dec 2018 21:53:33 +0100 Subject: [PATCH 098/208] Adds definition of ContentState.getEntityMap() (#31706) --- types/draft-js/draft-js-tests.tsx | 1 + types/draft-js/index.d.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index c0c64256fd..2375da74d4 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -315,6 +315,7 @@ ReactDOM.render( const editorState = EditorState.createEmpty(); const contentState = editorState.getCurrentContent(); +const entityMap = contentState.getEntityMap(); const rawContentState: RawDraftContentState = convertToRaw(contentState); rawContentState.blocks.forEach((block: RawDraftContentBlock) => { diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 4f2c34dd3a..4c00e7598f 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -9,6 +9,7 @@ // Santiago Vilar // Ulf Schwekendiek // Pablo Varela +// Claudio Procida // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -754,6 +755,7 @@ declare namespace Draft { createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState; getEntity(key: string): EntityInstance; + getEntityMap(): any; getLastCreatedEntityKey(): string; mergeEntityData(key: string, toMerge: { [key: string]: any }): ContentState; replaceEntityData(key: string, toMerge: { [key: string]: any }): ContentState; From 2b98b72dad31181b1dc87d6456490a93ec1f1714 Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 31 Dec 2018 13:42:51 -0800 Subject: [PATCH 099/208] 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 f1b04d0c9aade73ec41d6957ac15e64ced8c93af Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 31 Dec 2018 14:30:46 -0800 Subject: [PATCH 100/208] 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 db92425c03e131bd52307806f1b32e36974c7967 Mon Sep 17 00:00:00 2001 From: Ovidiu Bute Date: Tue, 1 Jan 2019 09:12:24 +0200 Subject: [PATCH 101/208] 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 102/208] [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 1e77f45f8fd9a00c336290d2b618dee5d4495aa0 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 1 Jan 2019 14:58:16 +0100 Subject: [PATCH 103/208] [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 104/208] [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 0fd7e1bc6fa780fae3c0d7aca9fb58e75ae12937 Mon Sep 17 00:00:00 2001 From: Carlos Date: Wed, 2 Jan 2019 02:41:21 +0800 Subject: [PATCH 105/208] [react-native-modal-dropdown] Add definitions (#31735) * react-native-modal-dropdown: initial definitions * fix the project path and export class * fix member-access --- types/react-native-modal-dropdown/index.d.ts | 44 +++++++++++++++++++ .../react-native-modal-dropdown-tests.tsx | 10 +++++ .../react-native-modal-dropdown/tsconfig.json | 25 +++++++++++ types/react-native-modal-dropdown/tslint.json | 3 ++ 4 files changed, 82 insertions(+) create mode 100644 types/react-native-modal-dropdown/index.d.ts create mode 100644 types/react-native-modal-dropdown/react-native-modal-dropdown-tests.tsx create mode 100644 types/react-native-modal-dropdown/tsconfig.json create mode 100644 types/react-native-modal-dropdown/tslint.json diff --git a/types/react-native-modal-dropdown/index.d.ts b/types/react-native-modal-dropdown/index.d.ts new file mode 100644 index 0000000000..01470ec1cf --- /dev/null +++ b/types/react-native-modal-dropdown/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for react-native-modal-dropdown 0.6 +// Project: https://github.com/sohobloo/react-native-modal-dropdown +// Definitions by: Carlos Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +import ModalDropdown = RNModalDropdown.ModalDropdown; +export = ModalDropdown; + +declare namespace RNModalDropdown { + interface PositionStyle { + left?: number; + right?: number; + width?: number; + } + interface ModalDropdownProps { + disabled?: boolean; + defaultIndex?: number; + defaultValue?: string; + options?: any[]; + animated?: boolean; + showsVerticalScrollIndicator?: boolean; + style?: any; + textStyle?: any; + dropdownStyle?: any; + dropdownTextStyle?: any; + dropdownTextHighlightStyle?: any; + adjustFrame?: (positionStyle: PositionStyle) => void; + renderRow?: (option: any, index: number, isSelected: boolean) => any; + renderSeparator?: () => any; + renderButtonText?: (text: any) => any; + onDropdownWillShow?: () => boolean; + onDropdownWillHide?: () => boolean; + onSelect?: (index: number, option: any) => void; + accessible?: boolean; + keyboardShouldPersistTaps?: "always" | "never" | "handled"; + } + + class ModalDropdown extends React.Component { + static default: typeof ModalDropdown; + } +} diff --git a/types/react-native-modal-dropdown/react-native-modal-dropdown-tests.tsx b/types/react-native-modal-dropdown/react-native-modal-dropdown-tests.tsx new file mode 100644 index 0000000000..685dd1f531 --- /dev/null +++ b/types/react-native-modal-dropdown/react-native-modal-dropdown-tests.tsx @@ -0,0 +1,10 @@ +import * as React from 'react'; +import ModalDropdown from "react-native-modal-dropdown"; + +class Test extends React.Component { + render() { + return ( + + ); + } +} diff --git a/types/react-native-modal-dropdown/tsconfig.json b/types/react-native-modal-dropdown/tsconfig.json new file mode 100644 index 0000000000..9800a11341 --- /dev/null +++ b/types/react-native-modal-dropdown/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-modal-dropdown-tests.tsx" + ] +} diff --git a/types/react-native-modal-dropdown/tslint.json b/types/react-native-modal-dropdown/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-native-modal-dropdown/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From bf4288fc9cc5cfab39a53e68e29661b4a3ccc8a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20K=C3=BChl?= Date: Tue, 1 Jan 2019 22:30:49 +0100 Subject: [PATCH 106/208] [noble-mac] Add types (#31786) * adds type definitions for noble-mac * [noble-mac]: fix linter issues and remove linter exceptions * [noble-mac]: fix dt-header issue --- types/noble-mac/index.d.ts | 125 +++++++++++++++++++++++++++++ types/noble-mac/noble-mac-tests.ts | 120 +++++++++++++++++++++++++++ types/noble-mac/tsconfig.json | 23 ++++++ types/noble-mac/tslint.json | 14 ++++ 4 files changed, 282 insertions(+) create mode 100644 types/noble-mac/index.d.ts create mode 100644 types/noble-mac/noble-mac-tests.ts create mode 100644 types/noble-mac/tsconfig.json create mode 100644 types/noble-mac/tslint.json diff --git a/types/noble-mac/index.d.ts b/types/noble-mac/index.d.ts new file mode 100644 index 0000000000..c960dc9693 --- /dev/null +++ b/types/noble-mac/index.d.ts @@ -0,0 +1,125 @@ +// Type definitions for noble-mac 0.0 +// Project: https://github.com/Timeular/noble-mac +// Definitions by: Seon-Wook Park +// Shantanu Bhadoria +// Luke Libraro +// Dan Chao +// Michal Lower +// Rob Moran +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import events = require("events"); + +export function startScanning(callback?: (error?: Error) => void): void; +export function startScanning(serviceUUIDs: string[], callback?: (error?: Error) => void): void; +export function startScanning(serviceUUIDs: string[], allowDuplicates: boolean, callback?: (error?: Error) => void): void; +export function stopScanning(callback?: () => void): void; + +export function on(event: "stateChange", listener: (state: string) => void): events.EventEmitter; +export function on(event: "scanStart" | "scanStop", listener: () => void): events.EventEmitter; +export function on(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; +export function on(event: string, listener: Function): events.EventEmitter; + +export function removeListener(event: "stateChange", listener: (state: string) => void): events.EventEmitter; +export function removeListener(event: "scanStart" | "scanStop", listener: () => void): events.EventEmitter; +export function removeListener(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; +export function removeListener(event: string, listener: Function): events.EventEmitter; + +export function removeAllListeners(event?: string): events.EventEmitter; + +export const state: string; + +export class Peripheral extends events.EventEmitter { + id: string; + uuid: string; + address: string; + addressType: string; + connectable: boolean; + advertisement: Advertisement; + rssi: number; + services: Service[]; + state: 'error' | 'connecting' | 'connected' | 'disconnecting' | 'disconnected'; + + connect(callback?: (error: string) => void): void; + disconnect(callback?: () => void): void; + updateRssi(callback?: (error: string, rssi: number) => void): void; + discoverServices(serviceUUIDs: string[], callback?: (error: string, services: Service[]) => void): void; + discoverAllServicesAndCharacteristics(callback?: (error: string, services: Service[], characteristics: Characteristic[]) => void): void; + discoverSomeServicesAndCharacteristics(serviceUUIDs: string[], characteristicUUIDs: string[], callback?: (error: string, services: Service[], characteristics: Characteristic[]) => void): void; + + readHandle(handle: Buffer, callback: (error: string, data: Buffer) => void): void; + writeHandle(handle: Buffer, data: Buffer, withoutResponse: boolean, callback: (error: string) => void): void; + toString(): string; + + on(event: "connect" | "disconnect", listener: (error: string) => void): this; + on(event: "rssiUpdate", listener: (rssi: number) => void): this; + on(event: "servicesDiscover", listener: (services: Service[]) => void): this; + on(event: string, listener: Function): this; +} + +export interface Advertisement { + localName: string; + serviceData: { + uuid: string, + data: Buffer + }; + txPowerLevel: number; + manufacturerData: Buffer; + serviceUuids: string[]; +} + +export class Service extends events.EventEmitter { + uuid: string; + name: string; + type: string; + includedServiceUuids: string[]; + characteristics: Characteristic[]; + + discoverIncludedServices(serviceUUIDs: string[], callback?: (error: string, includedServiceUuids: string[]) => void): void; + discoverCharacteristics(characteristicUUIDs: string[], callback?: (error: string, characteristics: Characteristic[]) => void): void; + toString(): string; + + on(event: "includedServicesDiscover", listener: (includedServiceUuids: string[]) => void): this; + on(event: "characteristicsDiscover", listener: (characteristics: Characteristic[]) => void): this; + on(event: string, listener: Function): this; +} + +export class Characteristic extends events.EventEmitter { + uuid: string; + name: string; + type: string; + properties: string[]; + descriptors: Descriptor[]; + + read(callback?: (error: string, data: Buffer) => void): void; + write(data: Buffer, notify: boolean, callback?: (error: string) => void): void; + broadcast(broadcast: boolean, callback?: (error: string) => void): void; + notify(notify: boolean, callback?: (error: string) => void): void; + discoverDescriptors(callback?: (error: string, descriptors: Descriptor[]) => void): void; + toString(): string; + subscribe(callback?: (error: string) => void): void; + unsubscribe(callback?: (error: string) => void): void; + + on(event: "read", listener: (data: Buffer, isNotification: boolean) => void): this; + on(event: "write", withoutResponse: boolean, listener: (error: string) => void): this; + on(event: "broadcast" | "notify", listener: (state: string) => void): this; + on(event: "descriptorsDiscover", listener: (descriptors: Descriptor[]) => void): this; + on(event: string, listener: Function): this; + on(event: string, option: boolean, listener: Function): this; +} + +export class Descriptor extends events.EventEmitter { + uuid: string; + name: string; + type: string; + + readValue(callback?: (error: string, data: Buffer) => void): void; + writeValue(data: Buffer, callback?: (error: string) => void): void; + toString(): string; + + on(event: "valueRead", listener: (error: string, data: Buffer) => void): this; + on(event: "valueWrite", listener: (error: string) => void): this; + on(event: string, listener: Function): this; +} diff --git a/types/noble-mac/noble-mac-tests.ts b/types/noble-mac/noble-mac-tests.ts new file mode 100644 index 0000000000..66e2657075 --- /dev/null +++ b/types/noble-mac/noble-mac-tests.ts @@ -0,0 +1,120 @@ +import noble = require("noble-mac"); + +function test_startScanning(): void { + "use strict"; + noble.startScanning(); + noble.startScanning((err) => {}); + noble.startScanning(["0x180d"]); + noble.startScanning(["0x180d"], (err) => {}); + noble.startScanning(["0x180d"], true); + noble.startScanning(["0x180d"], true, (err) => {}); +} +test_startScanning(); + +function test_stopScanning(): void { + "use strict"; + noble.stopScanning(); + noble.stopScanning(() => {}); +} +test_stopScanning(); + +noble.on("stateChange", (state: string): void => {}); +noble.on("scanStart", (): void => {}); +noble.on("scanStop", (): void => {}); +noble.on("discover", (peripheral: noble.Peripheral): void => { + peripheral.connect((error: string): void => {}); + peripheral.disconnect((): void => {}); +}); + +noble.removeListener("stateChange", (state: string): void => {}); +noble.removeListener("scanStart", (): void => {}); +noble.removeListener("scanStop", (): void => {}); +noble.removeListener("discover", (peripheral: noble.Peripheral): void => { + peripheral.connect((error: string): void => {}); + peripheral.disconnect((): void => {}); +}); + +noble.removeAllListeners("stateChange"); +noble.removeAllListeners("scanStart"); +noble.removeAllListeners("scanStop"); +noble.removeAllListeners("discover"); +noble.removeAllListeners(); + +const peripheral: noble.Peripheral = new noble.Peripheral(); +peripheral.uuid = "12ad4e81"; +peripheral.advertisement = { + localName: "device", + serviceData: { + uuid: "180a", + data: new Buffer(1) + }, + txPowerLevel: 1, + manufacturerData: new Buffer(1), + serviceUuids: ["0x180a", "0x180d"] +}; +peripheral.connect(); +peripheral.connect((error: string): void => {}); +peripheral.disconnect(); +peripheral.disconnect((): void => {}); +peripheral.updateRssi(); +peripheral.updateRssi((error: string, rssi: number): void => {}); +peripheral.discoverServices(["180d"]); +peripheral.discoverServices(["180d"], (error: string, services: noble.Service[]): void => {}); +peripheral.discoverAllServicesAndCharacteristics(); +peripheral.discoverAllServicesAndCharacteristics((error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); +peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"]); +peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"], (error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); +peripheral.readHandle(new Buffer(1), (error: string, data: Buffer): void => {}); +peripheral.writeHandle(new Buffer(1), new Buffer(1), true, (error: string): void => {}); +peripheral.on("connect", (error: string): void => {}); +peripheral.on("disconnect", (error: string): void => {}); +peripheral.on("rssiUpdate", (rssi: number): void => {}); +peripheral.on("servicesDiscover", (services: noble.Service[]): void => {}); + +const service: noble.Service = new noble.Service(); +service.uuid = "180a"; +service.name = ""; +service.type = ""; +service.includedServiceUuids = ["180d"]; +service.discoverIncludedServices(["180d"]); +service.discoverIncludedServices(["180d"], (error: string, includedServiceUuids: string[]): void => {}); +service.discoverCharacteristics(["2a38"]); +service.discoverCharacteristics(["2a38"], (error: string, characteristics: noble.Characteristic[]): void => {}); +service.on("includedServicesDiscover", (includedServiceUuids: string[]): void => {}); +service.on("characteristicsDiscover", (characteristics: noble.Characteristic[]): void => {}); + +const characteristic: noble.Characteristic = new noble.Characteristic(); +characteristic.uuid = "2a37"; +characteristic.name = ""; +characteristic.type = ""; +characteristic.properties = ["read", "notify"]; +characteristic.read(); +characteristic.read((error: string, data: Buffer): void => {}); +characteristic.write(new Buffer(1), true); +characteristic.write(new Buffer(1), true, (error: string): void => {}); +characteristic.broadcast(true); +characteristic.broadcast(true, (error: string): void => {}); +characteristic.notify(true); +characteristic.notify(true, (error: string): void => {}); +characteristic.discoverDescriptors(); +characteristic.discoverDescriptors((error: string, descriptors: noble.Descriptor[]): void => {}); +characteristic.on("read", (data: Buffer, isNotification: boolean): void => {}); +characteristic.on("write", true, (error: string): void => {}); +characteristic.on("broadcast", (state: string): void => {}); +characteristic.on("notify", (state: string): void => {}); +characteristic.on("descriptorsDiscover", (descriptors: noble.Descriptor[]): void => {}); +characteristic.subscribe(); +characteristic.subscribe((error: string) => {}); +characteristic.unsubscribe(); +characteristic.unsubscribe((error: string) => {}); + +const descriptor: noble.Descriptor = new noble.Descriptor(); +descriptor.uuid = ""; +descriptor.name = ""; +descriptor.type = ""; +descriptor.readValue(); +descriptor.readValue((error: string, data: Buffer): void => {}); +descriptor.writeValue(new Buffer(1)); +descriptor.writeValue(new Buffer(1), (error: string): void => {}); +descriptor.on("valueRead", (error: string, data: Buffer): void => {}); +descriptor.on("valueWrite", (error: string): void => {}); diff --git a/types/noble-mac/tsconfig.json b/types/noble-mac/tsconfig.json new file mode 100644 index 0000000000..4c10b7725a --- /dev/null +++ b/types/noble-mac/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", + "noble-mac-tests.ts" + ] +} diff --git a/types/noble-mac/tslint.json b/types/noble-mac/tslint.json new file mode 100644 index 0000000000..e2de850d06 --- /dev/null +++ b/types/noble-mac/tslint.json @@ -0,0 +1,14 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + } + } +} From 00fa3fc061227d57c6b42b9149deac686395bb39 Mon Sep 17 00:00:00 2001 From: TOGASHI Tomoki Date: Wed, 2 Jan 2019 07:18:30 +0900 Subject: [PATCH 107/208] [google.script.client-side] Add types (#31792) * [google.script.client-side] Add types * [google.script.client-side] Put version and enable header lint rule --- .../google.script.client-side-tests.ts | 39 +++++ types/google.script.client-side/index.d.ts | 151 ++++++++++++++++++ types/google.script.client-side/tsconfig.json | 23 +++ types/google.script.client-side/tslint.json | 3 + 4 files changed, 216 insertions(+) create mode 100644 types/google.script.client-side/google.script.client-side-tests.ts create mode 100644 types/google.script.client-side/index.d.ts create mode 100644 types/google.script.client-side/tsconfig.json create mode 100644 types/google.script.client-side/tslint.json diff --git a/types/google.script.client-side/google.script.client-side-tests.ts b/types/google.script.client-side/google.script.client-side-tests.ts new file mode 100644 index 0000000000..5e3c059c01 --- /dev/null +++ b/types/google.script.client-side/google.script.client-side-tests.ts @@ -0,0 +1,39 @@ +google.script.url.getLocation(location => { + location.hash; // $ExpectedType string + location.parameter; // $ExpectedType { [key: string]: string } + location.parameters; // $ExpectedType { [key: string]: ReadonlyArray } +}); + +google.script.history.push(null); +google.script.history.push({ timestamp: Date.now() }, { foo: 'bar', fiz: 'baz' }); +google.script.history.push({ timestamp: Date.now() }, { foo: ['bar', 'cat'], fiz: 'baz' }, 'anchor1'); + +google.script.history.replace(null); +google.script.history.replace({ timestamp: Date.now() }, { foo: 'bar', fiz: 'baz' }); +google.script.history.replace({ timestamp: Date.now() }, { foo: ['bar', 'cat'], fiz: 'baz' }, 'anchor1'); + +google.script.history.setChangeHandler(e => { + e.state; // $ExpectedType google.script.history.State + e.location.hash; // $ExpectedType string + e.location.parameter; // $ExpectedType { [key: string]: string } + e.location.parameters; // $ExpectedType { [key: string]: ReadonlyArray } +}); + +google.script.host.origin; // $ExpectType string +google.script.host.close(); +google.script.host.editor.focus(); +google.script.host.setHeight(450); +google.script.host.setWidth(300); + +google.script.run.withSuccessHandler(() => {}).executeScript({ message: 'test for google.script.run' }); + +google.script.run + .withSuccessHandler(value => {}) + .withFailureHandler(error => {}) + .getEmail(); + +google.script.run + .withSuccessHandler((value, userObject) => {}) + .withFailureHandler((error, userObject) => {}) + .withUserObject({}) + .getSomeData(Date.now(), { options: 'none' }, 'anchor1', true, null); diff --git a/types/google.script.client-side/index.d.ts b/types/google.script.client-side/index.d.ts new file mode 100644 index 0000000000..566fbb7397 --- /dev/null +++ b/types/google.script.client-side/index.d.ts @@ -0,0 +1,151 @@ +// Type definitions for Google Apps Script Client-side API 0.0 +// Project: https://developers.google.com/apps-script/guides/html/reference/host +// Definitions by: clomie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace google.script { + interface UrlLocation { + /** + * The string value of URL fragment after the # character, or an emptry string if no URL fragment is present + */ + hash: string; + + /** + * An object of key/value pairs that correspond to the URL request parameters. + * Only the first value will be returned for parameters that have multiple values. + * If no parameters are present, this will be an empty object. + */ + parameter: { [key: string]: string }; + + /** + * An object similar to location.parameter, but with an array of values for each key. + * If no parameters are present, this will be an empty object. + */ + parameters: { [key: string]: ReadonlyArray }; + } + + namespace url { + /** + * Gets a URL location object and passes it to the specified callback function (as the only argument). + * @param callback a client-side callback function to run, using the location object as the only argument. + */ + function getLocation(callback: (location: UrlLocation) => void): void; + } + + namespace history { + type State = object | null; + interface Query { + [key: string]: string | ReadonlyArray; + } + + /** + * Pushes the provided state object, URL parameters and URL fragment onto the browser history stack. + * @param stateObject An developer-defined object to be associated with a browser history event, and which resurfaces when the state is popped. + * Typically used to store application state information (such as page data) for future retrieval. + * @param params An object containing URL parameters to associate with this state. + * For example, {foo: “bar”, fiz: “baz”} equates to "?foo=bar&fiz=baz". + * Alternatively, arrays can be used: {foo: [“bar”, “cat”], fiz: “baz”} equates to "?foo=bar&foo=cat&fiz=baz". + * If null or undefined, the current URL parameters are not changed. If empty, the URL parameters are cleared. + * @param hash The string URL fragment appearing after the '#' character. + * If null or undefined, the current URL fragment is not changed. If empty, the URL fragment is cleared. + */ + function push(stateObject: State, params?: Query, hash?: string): void; + + /** + * Replaces the top event on the browser history stack with the provided (developer-defined) state object, URL parameters and URL fragment. + * @param stateObject An developer-defined object to be associated with a browser history event, and which resurfaces when the state is popped. + * Typically used to store application state information (such as page data) for future retrieval. + * @param params An object containing URL parameters to associate with this state. + * For example, {foo: “bar”, fiz: “baz”} equates to "?foo=bar&fiz=baz". + * Alternatively, arrays can be used: {foo: [“bar”, “cat”], fiz: “baz”} equates to "?foo=bar&foo=cat&fiz=baz". + * If null or undefined, the current URL parameters are not changed. If empty, the URL parameters are cleared. + * @param hash The string URL fragment appearing after the '#' character. + * If null or undefined, the current URL fragment is not changed. If empty, the URL fragment is cleared. + */ + function replace(stateObject: State, params?: Query, hash?: string): void; + + interface HistoryChangeEvent { + /** + * The state object associated with the popped event. + * This object is identical to the state object that used in the corresponding push() or replace() method that added the popped state to the history stack. + */ + state: State; + + /** + * A location object associated with the popped event + */ + location: UrlLocation; + } + + /** + * Sets a callback function to respond to changes in the browser history. + * @param callback a client-side callback function to run upon a history change event, using the event object as the only argument. + */ + function setChangeHandler(handler: (event: HistoryChangeEvent) => void): void; + } + + namespace host { + /** + * Provides the host domain, so scripts can set their origin correctly. + */ + const origin: string; + + /** + * Closes the current dialog or sidebar. + */ + function close(): void; + + namespace editor { + /** + * Switches browser focus from the dialog or sidebar to the Google Docs, Sheets, or Forms editor. + */ + function focus(): void; + } + + /** + * Sets the height of the current dialog. + * @param height the new height, in pixels + */ + function setHeight(height: number): void; + + /** + * Sets the width of the current dialog. + * @param width the new width, in pixels + */ + function setWidth(width: number): void; + } + + const run: Runner; + + interface Runner { + /** + * Executes the server-side Apps Script function with the corresponding name. + */ + [functionName: string]: (...args: any[]) => void; + + /** + * Sets a callback function to run if the server-side function throws an exception. + * Without a failure handler, failures are logged to the JavaScript console. + * To override this, call withFailureHandler(null) or supply a failure handler that does nothing. + * @param handler a client-side callback function to run if the server-side function throws an exception; + * the Error object is passed to the function as the first argument, and the user object (if any) is passed as a second argument + */ + withFailureHandler(handler: (error: Error, object?: any) => void): Runner; + + /** + * Sets a callback function to run if the server-side function returns successfully. + * @param handler a client-side callback function to run if the server-side function returns successfully; + * the server's return value is passed to the function as the first argument, and the user object (if any) is passed as a second argument + */ + withSuccessHandler(handler: (value?: any, object?: any) => void): Runner; + + /** + * Sets an object to pass as a second parameter to the success and failure handlers. + * @param object an object to pass as a second parameter to the success and failure handlers; + * because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. + * User objects cannot, however, be objects constructed with the new operator + */ + withUserObject(object: any): Runner; + } +} diff --git a/types/google.script.client-side/tsconfig.json b/types/google.script.client-side/tsconfig.json new file mode 100644 index 0000000000..83c99e2f06 --- /dev/null +++ b/types/google.script.client-side/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", + "google.script.client-side-tests.ts" + ] +} diff --git a/types/google.script.client-side/tslint.json b/types/google.script.client-side/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/google.script.client-side/tslint.json @@ -0,0 +1,3 @@ +{ + "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 108/208] 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 f516c9be01c554eb2e0fe6c0c0ff94dc9c7ca32e Mon Sep 17 00:00:00 2001 From: spacejack Date: Tue, 1 Jan 2019 18:04:14 -0500 Subject: [PATCH 109/208] 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 f35e50837d12ad8035ba0886ee75fd1976deab2a Mon Sep 17 00:00:00 2001 From: nossbigg Date: Mon, 31 Dec 2018 10:43:55 +0800 Subject: [PATCH 110/208] 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 111/208] 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 112/208] 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 113/208] 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 114/208] 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 ddb5f8dd220ffa4e419ee1aab3ce9865a59e5e2c Mon Sep 17 00:00:00 2001 From: Anjun Wang Date: Wed, 2 Jan 2019 11:46:19 +0800 Subject: [PATCH 115/208] [strange] add types (#31757) * [strange] add types * [strange] import as namespace * [strange] remove unused lint rule --- types/strange/index.d.ts | 317 +++++++++++++++++++++++++++++++++ types/strange/strange-tests.ts | 117 ++++++++++++ types/strange/tree.d.ts | 59 ++++++ types/strange/tsconfig.json | 24 +++ types/strange/tslint.json | 3 + 5 files changed, 520 insertions(+) create mode 100644 types/strange/index.d.ts create mode 100644 types/strange/strange-tests.ts create mode 100644 types/strange/tree.d.ts create mode 100644 types/strange/tsconfig.json create mode 100644 types/strange/tslint.json diff --git a/types/strange/index.d.ts b/types/strange/index.d.ts new file mode 100644 index 0000000000..8813c7de36 --- /dev/null +++ b/types/strange/index.d.ts @@ -0,0 +1,317 @@ +// Type definitions for strange 1.7 +// Project: https://github.com/moll/js-strange +// Definitions by: Anjun Wang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Range; + +/** + * Create a new range object with the given begin and end endpoints. + * You can also pass a two character string for bounds. Defaults to` "[]"` for + * an all inclusive range. + * + * You can use any value for endpoints. `Null` is considered infinity for + * values that don't have a special infinity type like `Number` has `Infinity`. + * + * An empty range is one where either of the endpoints is `undefined` + * (like `new Range`) or a range with two equivalent, but exculsive endpoints + * (`new Range(5, 5, "[)")`). + * + * @example + * var Range = require("strange") + * new Range(10, 20) // => {begin: 10, end: 20, bounds: "[]"} + * new Range(new Date(2000, 5, 18), new Date(2000, 5, 22)) + */ +declare const Range: RangeConstructor; + +interface RangeConstructor { + /** + * + * @param begin Range's beginning, or left endpoint. + * @param end Range's end, or right endpoint. + * @param bounds Range's bounds. + */ + new (begin?: T | null, end?: T | null, bounds?: Range.Bounds): Range; + + /** + * + * @param begin Range's beginning, or left endpoint. + * @param end Range's end, or right endpoint. + * @param bounds Range's bounds. + */ + (begin?: T | null, end?: T | null, bounds?: Range.Bounds): Range; + + /** + * Compares two range's beginnings. + * Returns `-1` if `a` begins before `b` begins, `0` if they're equal and `1` + * if `a` begins after `b`. + * + * @example + * Range.compareBeginToBegin(new Range(0, 10), new Range(5, 15)) // => -1 + * Range.compareBeginToBegin(new Range(0, 10), new Range(0, 15)) // => 0 + * Range.compareBeginToBegin(new Range(0, 10), new Range(0, 15, "()")) // => 1 + */ + compareBeginToBegin(a: Range, b: Range): -1 | 0 | 1; + + /** + * Compares the first range's beginning to the second's end. + * Returns `<0` if `a` begins before `b` ends, `0` if one starts where the other + * ends and `>1` if `a` begins after `b` ends. + * + * @example + * Range.compareBeginToEnd(new Range(0, 10), new Range(0, 5)) // => -1 + * Range.compareBeginToEnd(new Range(0, 10), new Range(-10, 0)) // => 0 + * Range.compareBeginToEnd(new Range(0, 10), new Range(-10, -5)) // => 1 + */ + compareBeginToEnd(a: Range, b: Range): -1 | 0 | 1; + + /** + * Compares two range's endings. + * Returns `-1` if `a` ends before `b` ends, `0` if they're equal and `1` + * if `a` ends after `b`. + * + * @example + * Range.compareEndToEnd(new Range(0, 10), new Range(5, 15)) // => -1 + * Range.compareEndToEnd(new Range(0, 10), new Range(5, 10)) // => 0 + * Range.compareEndToEnd(new Range(0, 10), new Range(5, 10, "()")) // => 1 + */ + compareEndToEnd(a: Range, b: Range): -1 | 0 | 1; + + /** + * Parses a string stringified by + * [`Range.prototype.toString`](#Range.prototype.toString). + * + * To have it also parse the endpoints to something other than a string, pass + * a function as the second argument. + * + * If you pass `Number` as the _parse_ function and the endpoints are + * unbounded, they'll be set to `Infinity` for easier computation. + * + * @example + * Range.parse("[a,z)") // => new Range("a", "z", "[)") + */ + parse(range: string): Range; + + /** + * Parses a string stringified by + * [`Range.prototype.toString`](#Range.prototype.toString). + * + * To have it also parse the endpoints to something other than a string, pass + * a function as the second argument. + * + * If you pass `Number` as the _parse_ function and the endpoints are + * unbounded, they'll be set to `Infinity` for easier computation. + * + * @example + * Range.parse("[42,69]", Number) // => new Range(42, 69) + * Range.parse("[15,]", Number) // => new Range(15, Infinity) + * Range.parse("(,3.14]", Number) // => new Range(-Infinity, 3.14, "(]") + */ + parse(range: string, parse: (endpoint: string) => U): Range; + + /** + * Merges two ranges and returns a range that encompasses both of them. + * The ranges don't have to be intersecting. + * + * @example + * Range.union(new Range(0, 5), new Range(5, 10)) // => new Range(0, 10) + * Range.union(new Range(0, 10), new Range(5, 15)) // => new Range(0, 15) + * + * var a = new Range(-5, 0, "()") + * var b = new Range(5, 10) + * Range.union(a, b) // => new Range(-5, 10, "(]") + */ + union(a: Range, b: Range): Range; + + readonly prototype: Range; +} + +interface Range { + /** + * Range's beginning, or left endpoint. + */ + begin?: T | null; + + /** + * Range's end, or right endpoint. + */ + end?: T | null; + + /** + * Range's bounds. + * + * Bounds signify whether the range includes or excludes that particular + * endpoint. + * + * Pair | Meaning + * -----|-------- + * `()` | open + * `[]` | closed + * `[)` | left-closed, right-open + * `(]` | left-open, right-closed + * + * @example + * new Range(1, 5).bounds // => "[]" + * new Range(1, 5, "[)").bounds // => "[)" + */ + bounds: Range.Bounds; + + /** + * Compares this range's beginning with the given value. + * Returns `-1` if this range begins before the given value, `0` if they're + * equal and `1` if this range begins after the given value. + * + * `null` is considered to signify negative infinity for non-numeric range + * endpoints. + * + * @example + * new Range(0, 10).compareBegin(5) // => -1 + * new Range(0, 10).compareBegin(0) // => 0 + * new Range(5, 10).compareBegin(0) // => 1 + * new Range(5, 10).compareBegin(null) // => 1 + */ + compareBegin(begin: T | null): -1 | 0 | 0; + + /** + * Compares this range's end with the given value. + * Returns `-1` if this range ends before the given value, `0` if they're + * equal and `1` if this range ends after the given value. + * + * `null` is considered to signify positive infinity for non-numeric range + * endpoints. + * + * @example + * new Range(0, 10).compareEnd(5) // => -1 + * new Range(0, 10).compareEnd(10) // => 0 + * new Range(0, 5).compareEnd(10) // => 1 + * new Range(0, 5).compareEnd(null) // => -1 + */ + compareEnd(end: T | null): -1 | 0 | 0; + + /** + * Check whether the range is empty. + * An empty range is one where either of the endpoints is `undefined` + * (like `new Range`) or a range with two equivalent, but exculsive endpoints + * (`new Range(5, 5, "[)")`). + * + * Equivalence is checked by using the `<` operators, so value objects will be + * coerced into something comparable by JavaScript. That usually means calling + * the object's `valueOf` function. + * + * @example + * new Range().isEmpty() // => true + * new Range(5, 5, "[)").isEmpty() // => true + * new Range(1, 10).isEmpty() // => false + */ + isEmpty(): boolean; + + /** + * Check whether the range is bounded. + * A bounded range is one where neither endpoint is `null` or `Infinity`. An + * empty range is considered bounded. + * + * @example + * new Range().isBounded() // => true + * new Range(5, 5).isBounded() // => true + * new Range(null, new Date(2000, 5, 18)).isBounded() // => false + * new Range(0, Infinity).isBounded() // => false + * new Range(-Infinity, Infinity).isBounded() // => false + */ + isBounded(): boolean; + + /** + * @alias isBounded + */ + isFinite(): boolean; + + /** + * Check whether the range is unbounded. + * An unbounded range is one where either endpoint is `null` or `Infinity`. An + * empty range is not considered unbounded. + * + * @example + * new Range().isUnbounded() // => false + * new Range(5, 5).isUnbounded() // => false + * new Range(null, new Date(2000, 5, 18)).isUnbounded() // => true + * new Range(0, Infinity).isUnbounded() // => true + * new Range(-Infinity, Infinity).isUnbounded() // => true + */ + isUnbounded(): boolean; + + /** + * @alias isUnbounded + */ + isInfinite(): boolean; + + /** + * Check if a given value is contained within this range. + * Returns `true` or `false`. + * + * @example + * new Range(0, 10).contains(5) // => true + * new Range(0, 10).contains(10) // => true + * new Range(0, 10, "[)").contains(10) // => false + */ + contains(value: T | null): boolean; + + /** + * Check if this range intersects with another. + * Returns `true` or `false`. + * + * Ranges that have common points intersect. Ranges that are consecutive and + * with *inclusive* endpoints are also intersecting. An empty range will never + * intersect. + * + * @example + * new Range(0, 10).intersects(new Range(5, 7)) // => true + * new Range(0, 10).intersects(new Range(10, 20)) // => true + * new Range(0, 10, "[)").intersects(new Range(10, 20)) // => false + * new Range(0, 10).intersects(new Range(20, 30)) // => false + */ + intersects(value: Range): boolean; + + /** + * Returns an array of the endpoints and bounds. + * + * Useful with [Egal.js](https://github.com/moll/js-egal) or other libraries + * that compare value objects by their `valueOf` output. + * + * @example + * new Range(1, 10, "[)").valueOf() // => [1, 10, "[)"] + */ + valueOf(): [T | null | undefined, T | null | undefined, Range.Bounds]; + + /** + * Stringifies a range in `[a,b]` format. + * + * This happens to match the string format used by [PostgreSQL's range type + * format](http://www.postgresql.org/docs/9.4/static/rangetypes.html). You can + * therefore use stRange.js to parse and stringify ranges for your database. + * + * @example + * new Range(1, 5).toString() // => "[1,5]" + * new Range(1, 10, "[)").toString() // => "[1,10)" + */ + toString(): string; + + /** + * Stringifies the range when passing it to `JSON.stringify`. + * This way you don't need to manually call `toString` when stringifying. + * + * @example + * JSON.stringify(new Range(1, 10)) // "\"[1,10]\"" + * + * @alias toString + */ + toJSON(): string; + + /** + * @alias toJSON + */ + inspect(): string; +} + +declare namespace Range { + type Endpoint = Date | number | string; + type Bounds = '()' | '[]' | '[)' | '(]'; +} diff --git a/types/strange/strange-tests.ts b/types/strange/strange-tests.ts new file mode 100644 index 0000000000..432911d0d4 --- /dev/null +++ b/types/strange/strange-tests.ts @@ -0,0 +1,117 @@ +import * as Range from 'strange'; +import * as RangeTree from 'strange/tree'; + +{ + new Range(); + new Range(1, Infinity); + new Range(null, 10); + new Range(undefined, 10); + new Range(1, 10, '[]'); + new Range(-Infinity, null, '[]'); + new Range(1, undefined, '[]'); + + Range(); + Range(1, Infinity); + Range(null, 10); + Range(undefined, 10); + Range(1, 10, '[]'); + Range(-Infinity, null, '[]'); + Range(1, undefined, '[]'); + + new Range(new Date(2000, 5, 18), new Date(2000, 5, 22)); + + new Range(0, 10).begin; + new Range(0, 10).end; + new Range(0, 10).bounds; + + new Range(0, 10).compareBegin(5); // => -1 + new Range(0, 10).compareBegin(0); // => 0 + new Range(5, 10).compareBegin(0); // => 1 + new Range(5, 10).compareBegin(null); // => 1 + + new Range(0, 10).compareEnd(5); // => -1 + new Range(0, 10).compareEnd(10); // => 0 + new Range(0, 5).compareEnd(10); // => 1 + new Range(0, 5).compareEnd(null); // => -1 + + new Range().isEmpty(); // => true + new Range(5, 5, "[)").isEmpty(); // => true + new Range(1, 10).isEmpty(); // => false + + new Range().isBounded(); // => true + new Range(5, 5).isBounded(); // => true + new Range(null, new Date(2000, 5, 18)).isBounded(); // => false + new Range(0, Infinity).isBounded(); // => false + new Range(-Infinity, Infinity).isBounded(); // => false + + new Range().isFinite(); // => true + new Range(5, 5).isFinite(); // => true + new Range(null, new Date(2000, 5, 18)).isFinite(); // => false + new Range(0, Infinity).isFinite(); // => false + new Range(-Infinity, Infinity).isFinite(); // => false + + new Range().isUnbounded(); // => false + new Range(5, 5).isUnbounded(); // => false + new Range(null, new Date(2000, 5, 18)).isUnbounded(); // => true + new Range(0, Infinity).isUnbounded(); // => true + new Range(-Infinity, Infinity).isUnbounded(); // => true + + new Range().isInfinite(); // => false + new Range(5, 5).isInfinite(); // => false + new Range(null, new Date(2000, 5, 18)).isInfinite(); // => true + new Range(0, Infinity).isInfinite(); // => true + new Range(-Infinity, Infinity).isInfinite(); // => true + + new Range(0, 10).contains(5); // => true + new Range(0, 10).contains(10); // => true + new Range(0, 10, "[)").contains(10); // => false + + new Range(0, 10).intersects(new Range(5, 7)); // => true + new Range(0, 10).intersects(new Range(10, 20)); // => true + new Range(0, 10, "[)").intersects(new Range(10, 20)); // => false + new Range(0, 10).intersects(new Range(20, 30)); // => false + + new Range(1, 10, "[)").valueOf(); // => [1, 10, "[)"] + + new Range(1, 5).toString(); // => "[1,5]" + new Range(1, 10, "[)").toString(); // => "[1,10)" + + JSON.stringify(new Range(1, 10)); // "\"[1,10]\"" + new Range(1, 10).toJSON(); // "\"[1,10]\"" + new Range(1, 10).inspect(); // "\"[1,10]\"" + + Range.compareBeginToBegin(new Range(0, 10), new Range(5, 15)); // => -1 + Range.compareBeginToBegin(new Range(0, 10), new Range(0, 15)); // => 0 + Range.compareBeginToBegin(new Range(0, 10), new Range(0, 15, "()")); // => 1 + + Range.compareBeginToEnd(new Range(0, 10), new Range(0, 5)); // => -1 + Range.compareBeginToEnd(new Range(0, 10), new Range(-10, 0)); // => 0 + Range.compareBeginToEnd(new Range(0, 10), new Range(-10, -5)); // => 1 + + Range.compareEndToEnd(new Range(0, 10), new Range(5, 15)); // => -1 + Range.compareEndToEnd(new Range(0, 10), new Range(5, 10)); // => 0 + Range.compareEndToEnd(new Range(0, 10), new Range(5, 10, "()")); // => 1 + + Range.parse("[a,z)"); // => new Range("a", "z", "[)") + Range.parse("[42,69]", Number); // => new Range(42, 69) + Range.parse("[15,]", Number); // => new Range(15, Infinity) + Range.parse("(,3.14]", Number); // => new Range(-Infinity, 3.14, "(]") + + Range.union(new Range(0, 5), new Range(5, 10)); // => new Range(0, 10) + Range.union(new Range(0, 10), new Range(5, 15)); // => new Range(0, 15) + + const a = new Range(-5, 0, "()"); + const b = new Range(5, 10); + Range.union(a, b); // => new Range(-5, 10, "(]") +} + +{ + const left = new RangeTree([new Range(-5, 0)]); + const right = new RangeTree([new Range(5, 10)]); + const root = new RangeTree([new Range(0, 5), new Range(0, 10)], left, right); + root.search(7); // => [new Range(0, 10), new Range(5, 10)] + root.search(new Range(8, 9)); // => [new Range(5, 10), new Range(0, 10)] + + const ranges = [new Range(0, 10), new Range(20, 30), new Range(40, 50)]; + RangeTree.from(ranges).search(42); // => [new Range(40, 50)] +} diff --git a/types/strange/tree.d.ts b/types/strange/tree.d.ts new file mode 100644 index 0000000000..f768a3c727 --- /dev/null +++ b/types/strange/tree.d.ts @@ -0,0 +1,59 @@ +import Range = require('./index'); + +export = RangeTree; + +/** + * Create an interval tree node. + * + * For creating a binary search tree out of an array of ranges, you might want + * to use [`RangeTree.from`](#RangeTree.from). + * + * @example + * var RangeTree = require("strange/tree") + * var left = new RangeTree([new Range(-5, 0)]) + * var right = new RangeTree([new Range(5, 10)]) + * var root = new RangeTree([new Range(0, 5), new Range(0, 10)], left, right) + * root.search(7) // => [new Range(0, 10), new Range(5, 10)] + */ +declare class RangeTree { + /** + * Create an interval tree (implemented as an augmented binary search tree) + * from an array of ranges. + * Returns a [`RangeTree`](#RangeTree) you can search on. + * + * If you need to relate the found ranges to other data, add some properties + * directly to every range _or_ use JavaScript's `Map` or `WeakMap` to relate + * extra data to those range instances. + * + * @example + * var ranges = [new Range(0, 10), new Range(20, 30), new Range(40, 50)] + * RangeTree.from(ranges).search(42) // => [new Range(40, 50)] + */ + static from(ranges: Array>): RangeTree; + + /** + * Ranges of current tree node. + */ + private keys: Array>; + private left: RangeTree | null; + private right: RangeTree | null; + + constructor(ranges: Range | Array>, left?: RangeTree | null, right?: RangeTree | null); + + /** + * Search for ranges that include the given value or, given a range, intersect + * with it. + * Returns an array of matches or an empty one if no range contained or + * intersected with the given value. + * + * @example + * var tree = RangeTree.from([new Range(40, 50)]) + * tree.search(42) // => [new Range(40, 50)] + * tree.search(13) // => [] + * tree.search(new Range(30, 42)) // => [new Range(40, 50)] + */ + search(valueOrRange: null | T | Range): Array>; +} + +declare namespace RangeTree { +} diff --git a/types/strange/tsconfig.json b/types/strange/tsconfig.json new file mode 100644 index 0000000000..5267392b24 --- /dev/null +++ b/types/strange/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "strange-tests.ts", + "tree.d.ts" + ] +} diff --git a/types/strange/tslint.json b/types/strange/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/strange/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 0e62835aeacfe8262d1d985a8bfc8c45a1c617c1 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 1 Jan 2019 23:32:00 -0500 Subject: [PATCH 116/208] 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 117/208] 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 118/208] 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 119/208] 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 120/208] 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 121/208] 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 122/208] 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 123/208] 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 124/208] 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 125/208] 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 126/208] 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 127/208] 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 128/208] 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 cf569891f458d6bd00848d2f1ee929c02adecb53 Mon Sep 17 00:00:00 2001 From: Sameer KC Date: Wed, 2 Jan 2019 12:46:40 +0100 Subject: [PATCH 129/208] 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 130/208] 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 131/208] 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 132/208] 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 133/208] [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 134/208] 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 135/208] 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 136/208] 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 8673a2187e6c57443fbd8955e7b2fe32741bafe3 Mon Sep 17 00:00:00 2001 From: Martin Artola Date: Wed, 2 Jan 2019 17:26:31 +0100 Subject: [PATCH 137/208] Add QueryResponseCache --- types/relay-runtime/index.d.ts | 18 ++++++++++++++++++ types/relay-runtime/relay-runtime-tests.tsx | 4 ++++ 2 files changed, 22 insertions(+) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index dbafde4fe1..27ae20706c 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -138,6 +138,24 @@ export type SubscribeFunction = ( observer: LegacyObserver ) => RelayObservable | Disposable; +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayQueryResponseCache +// Version: Relay 1.3.0 +// File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayQueryResponseCache.js +// ~~~~~~~~~~~~~~~~~~~~~ + +/** + * A cache for storing query responses, featuring: + * - `get` with TTL + * - cache size limiting, with least-recently *updated* entries purged first + */ +export class QueryResponseCache { + constructor(options: {size: number; ttl: number}); + clear(): void; + get(queryID: string, variables: Variables): QueryPayload | null; + set(queryID: string, variables: Variables, payload: QueryPayload): void; +} + // ~~~~~~~~~~~~~~~~~~~~~ // RelayStoreTypes // Version: Relay 1.3.0 diff --git a/types/relay-runtime/relay-runtime-tests.tsx b/types/relay-runtime/relay-runtime-tests.tsx index 72f262cbfa..ff714ce4ee 100644 --- a/types/relay-runtime/relay-runtime-tests.tsx +++ b/types/relay-runtime/relay-runtime-tests.tsx @@ -7,6 +7,7 @@ import { ViewerHandler, RecordSourceInspector, commitLocalUpdate, + QueryResponseCache, ROOT_ID, } from "relay-runtime"; @@ -33,6 +34,9 @@ function fetchQuery(operation: any, variables: { [key: string]: string }, cacheC // Create a network layer from the fetch function const network = Network.create(fetchQuery); +// Create a cache for storing query responses +const cache = new QueryResponseCache({size: 250, ttl: 60000}); + // ~~~~~~~~~~~~~~~~~~~~~ // Environment // ~~~~~~~~~~~~~~~~~~~~~ From 283edb4db7fa99ea33db2f7dc740865aa9dc9b25 Mon Sep 17 00:00:00 2001 From: Nathanael McDaniel Date: Wed, 2 Jan 2019 10:35:16 -0600 Subject: [PATCH 138/208] 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 72d8ba2ffc7b2d35bd66b78efb763226ae41e642 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 2 Jan 2019 09:03:35 -0800 Subject: [PATCH 139/208] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d6b8bde545..026994fdd5 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. -*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md) and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!* +*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!* ## What are declaration files? From 82a243caea68d65ea3331f852534363cff90ac4f Mon Sep 17 00:00:00 2001 From: Retsam Date: Thu, 20 Dec 2018 16:20:20 -0500 Subject: [PATCH 140/208] 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 addf196db4395260067814135843abd9de7e973b Mon Sep 17 00:00:00 2001 From: Andrew Petersen Date: Wed, 2 Jan 2019 13:08:16 -0500 Subject: [PATCH 141/208] [pseudo-audio-param] remove lint `rules`, fix optional fn signature --- types/pseudo-audio-param/index.d.ts | 2 +- types/pseudo-audio-param/tslint.json | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/types/pseudo-audio-param/index.d.ts b/types/pseudo-audio-param/index.d.ts index d1ef1dde93..330fc642ed 100644 --- a/types/pseudo-audio-param/index.d.ts +++ b/types/pseudo-audio-param/index.d.ts @@ -27,7 +27,7 @@ declare class PseudoAudioParam { * Apply scheduled methods to the provided audioParam. If reset is `true`, * cancel all events of AudioParam before applying */ - applyTo(audioParam: AudioParam, reset: boolean): PseudoAudioParam; + applyTo(audioParam: AudioParam, reset?: boolean): PseudoAudioParam; setValueAtTime(value: number, time: number): PseudoAudioParam; linearRampToValueAtTime(value: number, time: number): PseudoAudioParam; diff --git a/types/pseudo-audio-param/tslint.json b/types/pseudo-audio-param/tslint.json index c9579fee14..d88586e5bd 100644 --- a/types/pseudo-audio-param/tslint.json +++ b/types/pseudo-audio-param/tslint.json @@ -1,7 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-single-declare-module": false, - "no-declare-current-package": false - } + "extends": "dtslint/dt.json" } From 882d354de4242e1808c42329a3ed146ac1245669 Mon Sep 17 00:00:00 2001 From: jlmessenger Date: Wed, 2 Jan 2019 13:12:26 -0500 Subject: [PATCH 142/208] [@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 143/208] 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 144/208] 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 145/208] 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 146/208] 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 147/208] 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 148/208] 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 149/208] 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 150/208] 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 151/208] 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 152/208] 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 153/208] [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 154/208] 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 155/208] 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 156/208] 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 157/208] 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 158/208] 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 159/208] 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 160/208] 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 161/208] 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 162/208] 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 163/208] 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 164/208] 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 165/208] 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 166/208] 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 167/208] 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 168/208] 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 169/208] 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 170/208] [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 171/208] 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 172/208] 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 173/208] 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 174/208] [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 175/208] [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 176/208] 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 177/208] 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 178/208] 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 179/208] 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 180/208] [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 | 204 +++++++++++++------------ types/stellar-sdk/stellar-sdk-tests.ts | 12 ++ 2 files changed, 118 insertions(+), 98 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; - destination: string; - startingBalance: string | number; - } - interface CreateAccountOptions { + interface CreateAccount extends Operation { + destination: string; + startingBalance: string; + } + 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 181/208] 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 182/208] 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 183/208] 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 184/208] [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 185/208] 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 186/208] 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 187/208] 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 188/208] 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 189/208] 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 190/208] 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 191/208] 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 192/208] 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 193/208] 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 `