From 6187a17f6d944d1c7b57bb8c3b2ee472fe3cc9ee Mon Sep 17 00:00:00 2001 From: Alexandre Parent Date: Tue, 20 Nov 2018 19:25:52 -0500 Subject: [PATCH 001/155] Added a use for expect 'checker' with a callback I often use expect(Object, CallbackHandler) because expect((Response) => any, CallbackHandler) doesn't exist. On the other hand, making callback nullable will allow those using it without callback to keep doing it. --- types/supertest/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 77418352f9..5ac03df42d 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -24,7 +24,7 @@ declare namespace supertest { serverAddress(app: any, path: string): string; expect(status: number, callback?: CallbackHandler): this; expect(status: number, body: any, callback?: CallbackHandler): this; - expect(checker: (res: Response) => any): this; + expect(checker: (res: Response) => any, callback?: CallbackHandler): this; expect(body: string, callback?: CallbackHandler): this; expect(body: RegExp, callback?: CallbackHandler): this; expect(body: Object, callback?: CallbackHandler): this; From 3daac759f4ce410664691073d7a16f735e5fe66a Mon Sep 17 00:00:00 2001 From: Benjamin Lupton Date: Wed, 21 Nov 2018 21:46:45 +1100 Subject: [PATCH 002/155] ansicolors: accurate types with recursion support --- types/ansicolors/index.d.ts | 44 +++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/types/ansicolors/index.d.ts b/types/ansicolors/index.d.ts index 6750283895..e82fb47dd7 100644 --- a/types/ansicolors/index.d.ts +++ b/types/ansicolors/index.d.ts @@ -1,8 +1,44 @@ // Type definitions for ansicolors // Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten +// Definitions by: Benjamin Arthur Lupton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare var colors: { [index: string]: (s: string) => string; }; -export = colors; +interface Colors extends String { + white: Colors + black: Colors + blue: Colors + cyan: Colors + green: Colors + magenta: Colors + red: Colors + yellow: Colors + brightBlack: Colors + brightRed: Colors + brightGreen: Colors + brightYellow: Colors + brightBlue: Colors + brightMagenta: Colors + brightCyan: Colors + brightWhite: Colors + bgBlack: Colors + bgRed: Colors + bgGreen: Colors + bgYellow: Colors + bgBlue: Colors + bgMagenta: Colors + bgCyan: Colors + bgWhite: Colors + bgBrightBlack: Colors + bgBrightRed: Colors + bgBrightGreen: Colors + bgBrightYellow: Colors + bgBrightBlue: Colors + bgBrightMagenta: Colors + bgBrightCyan: Colors + bgBrightWhite: Colors + open: Colors + close: Colors + colors: Colors +} +declare var colors: Colors +export default colors From cb3647d767af0964db8616dda47adc4ac0a90f5c Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 21 Nov 2018 14:30:25 -0500 Subject: [PATCH 003/155] Added missing methods and properties along with result type for CommandCursor --- types/mongodb/index.d.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index ab4d2f4c02..458aef1fc5 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -19,6 +19,7 @@ // Mikael Lirbank // Hector Ribes // Florian Richter +// Erik Christensen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -450,7 +451,7 @@ export class Db extends EventEmitter { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -1578,24 +1579,30 @@ export class AggregationCursor extends Readable { unwind(field: string): AggregationCursor; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ +export type CommandCursorResult = any | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(): Promise; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#batchSize */ batchSize(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#clone */ clone(): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#close */ - close(): Promise; - close(callback: MongoCallback): void; + close(): Promise; + close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#each */ - each(callback: MongoCallback): void; + each(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#maxTimeMS */ maxTimeMS(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#next */ - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#rewind */ From 398bd65886d481fdc91a49591a5b18ceab699569 Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 21 Nov 2018 14:43:15 -0500 Subject: [PATCH 004/155] Remove inaccurate deprecation warning --- types/mongodb/index.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 458aef1fc5..ca7b331f5b 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -45,10 +45,7 @@ export class MongoClient extends EventEmitter { static connect(uri: string, callback: MongoCallback): void; static connect(uri: string, options?: MongoClientOptions): Promise; static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; - /** - * @deprecated - * http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect - */ + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */ connect(): Promise; connect(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */ From a57ef63d3cb13e22b83b61784a7e35e0702863dd Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 21 Nov 2018 15:21:03 -0500 Subject: [PATCH 005/155] Added missing index spec and collation document interfaces --- types/mongodb/index.d.ts | 50 ++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index ca7b331f5b..a217b0a605 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -655,9 +655,9 @@ export interface Collection { createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */ - createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise; - createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise; + createIndexes(indexSpecs: IndexSpecification[], options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */ deleteMany(filter: FilterQuery, callback: MongoCallback): void; deleteMany(filter: FilterQuery, options?: CommonOptions): Promise; @@ -1074,7 +1074,7 @@ export interface CollectionAggregationOptions { promoteLongs?: boolean; promoteValues?: boolean; promoteBuffers?: boolean; - collation?: Object; + collation?: CollationDocument; comment?: string session?: ClientSession; @@ -1311,7 +1311,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1430,7 +1430,7 @@ export class Cursor extends Readable { close(): Promise; close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#collation */ - collation(value: Object): Cursor; + collation(value: CollationDocument): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#comment */ comment(value: string): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */ @@ -1729,7 +1729,7 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } @@ -1780,3 +1780,39 @@ export class Logger { // Set the current log level static setLevel(level: string): void } + +/** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ +export interface CollationDocument { + locale: string; + strength?: number; + caseLevel?: boolean; + caseFirst?: boolean; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; + +} + +/** https://docs.mongodb.com/manual/reference/command/createIndexes/ */ +export interface IndexSpecification { + key: object; + name?: string; + background?: boolean; + unique?: boolean; + partialFilterExpression?: object; + sparse?: boolean; + expireAfterSeconds?: number; + storageEngine?: object; + weights?: object; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + min?: number; + max?: number; + bucketSize?: number; + collation?: CollationDocument; +} From a72081e2b5cdc37d2e47acec4b1526250093575a Mon Sep 17 00:00:00 2001 From: Peter Safranek Date: Wed, 21 Nov 2018 15:07:50 -0800 Subject: [PATCH 006/155] [gulp-json-validator] Introduce typings for gulp-json-validator --- .../gulp-json-validator-tests.ts | 6 +++++ types/gulp-json-validator/index.d.ts | 14 +++++++++++ types/gulp-json-validator/tsconfig.json | 23 +++++++++++++++++++ types/gulp-json-validator/tslint.json | 6 +++++ 4 files changed, 49 insertions(+) create mode 100644 types/gulp-json-validator/gulp-json-validator-tests.ts create mode 100644 types/gulp-json-validator/index.d.ts create mode 100644 types/gulp-json-validator/tsconfig.json create mode 100644 types/gulp-json-validator/tslint.json diff --git a/types/gulp-json-validator/gulp-json-validator-tests.ts b/types/gulp-json-validator/gulp-json-validator-tests.ts new file mode 100644 index 0000000000..74a00f03da --- /dev/null +++ b/types/gulp-json-validator/gulp-json-validator-tests.ts @@ -0,0 +1,6 @@ +import gulpJsonValidator = require("gulp-json-validator"); + +gulpJsonValidator(); // $ExpectType ReadWriteStream +gulpJsonValidator({}); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: true }); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: false }); // $ExpectType ReadWriteStream diff --git a/types/gulp-json-validator/index.d.ts b/types/gulp-json-validator/index.d.ts new file mode 100644 index 0000000000..26e31d8b43 --- /dev/null +++ b/types/gulp-json-validator/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for gulp-json-validator 1.2 +// Project: https://github.com/jackyjieliu/gulp-json-validator +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface GulpJsonValidatorOptions { + allowDuplicatedKeys?: boolean; +} + +declare function gulpJsonValidator(option?: GulpJsonValidatorOptions): NodeJS.ReadWriteStream; + +export = gulpJsonValidator; diff --git a/types/gulp-json-validator/tsconfig.json b/types/gulp-json-validator/tsconfig.json new file mode 100644 index 0000000000..76ee50c184 --- /dev/null +++ b/types/gulp-json-validator/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", + "gulp-json-validator-tests.ts" + ] +} diff --git a/types/gulp-json-validator/tslint.json b/types/gulp-json-validator/tslint.json new file mode 100644 index 0000000000..702f9354fc --- /dev/null +++ b/types/gulp-json-validator/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } +} From 809fc1d291a42de5da96d6fa03796452bcde1c82 Mon Sep 17 00:00:00 2001 From: feinoujc Date: Wed, 21 Nov 2018 21:33:29 -0500 Subject: [PATCH 007/155] add graphql-fields typings --- types/graphql-fields/graphql-fields-tests.ts | 8 +++++++ types/graphql-fields/index.d.ts | 18 +++++++++++++++ types/graphql-fields/tsconfig.json | 24 ++++++++++++++++++++ types/graphql-fields/tslint.json | 1 + 4 files changed, 51 insertions(+) create mode 100644 types/graphql-fields/graphql-fields-tests.ts create mode 100644 types/graphql-fields/index.d.ts create mode 100644 types/graphql-fields/tsconfig.json create mode 100644 types/graphql-fields/tslint.json diff --git a/types/graphql-fields/graphql-fields-tests.ts b/types/graphql-fields/graphql-fields-tests.ts new file mode 100644 index 0000000000..811fe25ab2 --- /dev/null +++ b/types/graphql-fields/graphql-fields-tests.ts @@ -0,0 +1,8 @@ +import { GraphQLResolveInfo } from 'graphql'; +import graphqlFields = require('graphql-fields'); + +const info = ({} as any) as GraphQLResolveInfo; + +const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true }); +const fieldsWithoutTypeName = graphqlFields(info, {}, { excludedFields: ['__typename'] }); +graphqlFields(info); diff --git a/types/graphql-fields/index.d.ts b/types/graphql-fields/index.d.ts new file mode 100644 index 0000000000..19e7f21dc4 --- /dev/null +++ b/types/graphql-fields/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for graphql-fields 1.3 +// Project: https://github.com/robrichard/graphql-fields#readme +// Definitions by: feinoujc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { GraphQLResolveInfo } from 'graphql'; + +declare function graphqlFields(info: GraphQLResolveInfo, obj?: object, opts?: graphqlFields.Options): any; + +declare namespace graphqlFields { + interface Options { + processArguments?: boolean; + excludedFields?: string[]; + } +} + +export = graphqlFields; diff --git a/types/graphql-fields/tsconfig.json b/types/graphql-fields/tsconfig.json new file mode 100644 index 0000000000..826e200b41 --- /dev/null +++ b/types/graphql-fields/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "esnext.asynciterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphql-fields-tests.ts" + ] +} diff --git a/types/graphql-fields/tslint.json b/types/graphql-fields/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-fields/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4af88ab850423bf48f34057d0009d0dc786e0d23 Mon Sep 17 00:00:00 2001 From: Ben Frengley Date: Thu, 22 Nov 2018 16:24:15 +1300 Subject: [PATCH 008/155] [@types/mapbox-gl] Fix source type in source events + indentation fix --- types/mapbox-gl/index.d.ts | 2 +- types/mapbox-gl/mapbox-gl-tests.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 91fb68cd96..f3389876b9 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1071,7 +1071,7 @@ declare namespace mapboxgl { export interface MapSourceDataEvent extends MapboxEvent { dataType: 'source'; isSourceLoaded: boolean; - source: Style; + source: Source; sourceId: string; sourceDataType: 'metadata' | 'content'; tile: any; diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index 422b255900..d119c76bd5 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -465,10 +465,10 @@ expectType(mapboxgl.Point.convert(pointlike)); expectType((url: string) => ({ url })); expectType((url: string, resourceType: mapboxgl.ResourceType) => ({ - url, - credentials: 'same-origin', - headers: { 'Accept-Encoding': 'compress' }, - method: 'POST', + url, + credentials: 'same-origin', + headers: { 'Accept-Encoding': 'compress' }, + method: 'POST', collectResourceTiming: true, })); From 75dc5a9ca427435bf3d0b79a4fd6910f6a1b7b80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dennis=20M=C3=BCnch?= Date: Thu, 22 Nov 2018 09:33:58 +0100 Subject: [PATCH 009/155] add parameter [decapitalize=false] to camelize https://github.com/epeli/underscore.string#camelizestring-decapitalizefalse--string --- types/underscore.string/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/underscore.string/index.d.ts b/types/underscore.string/index.d.ts index 2d067679d5..eb0774b49a 100644 --- a/types/underscore.string/index.d.ts +++ b/types/underscore.string/index.d.ts @@ -207,7 +207,7 @@ declare module 'underscore' { * ('-moz-transform') => 'MozTransform' * @param str */ - camelize(str: string): string; + camelize(str: string, decapitalize?: boolean): string; /** * Converts a camelized or dasherized string into an underscored one. From b4a016ba645a65f8e16dcefdfcb260d1ce2e238d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dennis=20M=C3=BCnch?= Date: Thu, 22 Nov 2018 09:44:42 +0100 Subject: [PATCH 010/155] [@types/underscore.string] reflect change within test _.camelize('-moz-transform'); _.camelize('-moz-transform', true); --- types/underscore.string/underscore.string-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/underscore.string/underscore.string-tests.ts b/types/underscore.string/underscore.string-tests.ts index 545f6362d6..5b827cd880 100644 --- a/types/underscore.string/underscore.string-tests.ts +++ b/types/underscore.string/underscore.string-tests.ts @@ -52,6 +52,7 @@ _.succ('A'); _.titleize('my name is epeli'); _.camelize('-moz-transform'); +_.camelize('-moz-transform', true); _.classify('some_class_name'); From bd6515d5871238514dab001bcf0c062f0f25d721 Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Thu, 22 Nov 2018 16:34:26 +0000 Subject: [PATCH 011/155] [cached-path-relative] Add cached-path-relative@1.0.2 definition --- .../cached-path-relative-tests.ts | 7 ++++++ types/cached-path-relative/index.d.ts | 8 +++++++ types/cached-path-relative/tsconfig.json | 23 +++++++++++++++++++ types/cached-path-relative/tslint.json | 1 + 4 files changed, 39 insertions(+) create mode 100644 types/cached-path-relative/cached-path-relative-tests.ts create mode 100644 types/cached-path-relative/index.d.ts create mode 100644 types/cached-path-relative/tsconfig.json create mode 100644 types/cached-path-relative/tslint.json diff --git a/types/cached-path-relative/cached-path-relative-tests.ts b/types/cached-path-relative/cached-path-relative-tests.ts new file mode 100644 index 0000000000..22e6af97df --- /dev/null +++ b/types/cached-path-relative/cached-path-relative-tests.ts @@ -0,0 +1,7 @@ +import cachedPathRelative = require("cached-path-relative"); + +function browserifyTest() { + const file = "file.txt"; + const m1: string = cachedPathRelative("./", file).replace(/\\/g, '/'); + return m1; +} diff --git a/types/cached-path-relative/index.d.ts b/types/cached-path-relative/index.d.ts new file mode 100644 index 0000000000..56076870bc --- /dev/null +++ b/types/cached-path-relative/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for cached-path-relative 1.0 +// Project: https://github.com/ashaffer/cached-path-relative +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function cachedPathRelative(from: string, to: string): string; + +export = cachedPathRelative; diff --git a/types/cached-path-relative/tsconfig.json b/types/cached-path-relative/tsconfig.json new file mode 100644 index 0000000000..e69970c325 --- /dev/null +++ b/types/cached-path-relative/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", + "cached-path-relative-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cached-path-relative/tslint.json b/types/cached-path-relative/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cached-path-relative/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From a133ea37430313b85c65bbc775ba909c58e40a30 Mon Sep 17 00:00:00 2001 From: Markus Lasermann Date: Thu, 22 Nov 2018 17:56:50 +0100 Subject: [PATCH 012/155] add types for https://github.com/zesik/react-splitter-layout --- types/react-splitter-layout/index.d.ts | 100 ++++++++++++++++++ .../react-splitter-layout-tests.tsx | 17 +++ types/react-splitter-layout/tsconfig.json | 25 +++++ types/react-splitter-layout/tslint.json | 1 + 4 files changed, 143 insertions(+) create mode 100644 types/react-splitter-layout/index.d.ts create mode 100644 types/react-splitter-layout/react-splitter-layout-tests.tsx create mode 100644 types/react-splitter-layout/tsconfig.json create mode 100644 types/react-splitter-layout/tslint.json diff --git a/types/react-splitter-layout/index.d.ts b/types/react-splitter-layout/index.d.ts new file mode 100644 index 0000000000..ec25b5fe1a --- /dev/null +++ b/types/react-splitter-layout/index.d.ts @@ -0,0 +1,100 @@ +// Type definitions for react-splitter-layout v3.0.1 +// Project: https://github.com/zesik/react-splitter-layout#readme +// Definitions by: Markus Lasermann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.1.6 + +import * as React from "react"; + +export default SplitterLayout; + +declare class SplitterLayout extends React.PureComponent { +} + +type TPrimaryIndex = 0|1; + +export interface SplitterLayoutProps { + /** + * Custom CSS class name applied to the layout div. + * You can use this to customize layout style. + * Refers to the original stylesheet to see what you can customize. + */ + customClassName?: string; + + /** + * Determine whether the layout should be a horizontal split or a vertical split. + * + * @default false + */ + vertical?: boolean; + + /** + * Determine whether the width of each pane should be calculated in percentage or by pixels. + * The default value is false, which means width is calculated in pixels. + * + * @default false + */ + percentage?: boolean; + + /** + * Index of the primary pane. + * Since SplitterLayout supports at most 2 children, only 0 or 1 is allowed. + * + * A primary pane is used to show users primary content, while a secondary pane is the other pane. + * When window size changes and percentage is set to false, primary pane's size is flexible + * and secondary pane's size is kept unchanged. However, when the window size is not enough + * for showing both minimal primary pane and minimal secondary pane, + * the primary pane's size is served first. + * + * @default 0 + */ + primaryIndex?: TPrimaryIndex; + + /** + * Minimal size of primary pane. + * When percentage is set to false, this value is pixel size (25 means 25px). + * When percentage is set to true, this value is percentage (25 means 25%). + * + * @default 0 + */ + primaryMinSize?: number; + + /** + * Minimal size of secondary pane. + */ + secondaryMinSize?: number; + + /** + * Initial size of secondary pane when page loads. + * If this prop is not defined, SplitterLayout tries to split the layout with equal sizes. + * (Note: equal size may not apply when there are nested layouts.) + * + * @default undefined + */ + secondaryInitialSize?: number; + + /** + * Called when dragging is started. + * + * No parameter will be passed to event handlers. + */ + onDragStart?: () => void; + + /** + * Called when dragging finishes. + * + * No parameter will be passed to event handlers. + */ + onDragEnd?: () => void; + + /** + * Called when the size of secondary pane is changed. + * + * Event handlers will be passed with a single parameter of number type representing + * new size of secondary pane. + * When percentage is set to false, the value is in pixel size. + * When percentage is set to true, the value is in percentage. + */ + onSecondaryPaneSizeChange?: (value: number) => void; +} + diff --git a/types/react-splitter-layout/react-splitter-layout-tests.tsx b/types/react-splitter-layout/react-splitter-layout-tests.tsx new file mode 100644 index 0000000000..1f97db7077 --- /dev/null +++ b/types/react-splitter-layout/react-splitter-layout-tests.tsx @@ -0,0 +1,17 @@ +import * as React from "react"; +import SplitterLayout, {SplitterLayoutProps} from "react-splitter-layout"; + +export class SplitterLayoutTest extends React.PureComponent<{}> { + render(): JSX.Element { + const props: SplitterLayoutProps = { + percentage: true, + secondaryInitialSize: 30, + }; + return ( + +
1st
+
2nd
+
+ ); + } +} diff --git a/types/react-splitter-layout/tsconfig.json b/types/react-splitter-layout/tsconfig.json new file mode 100644 index 0000000000..e268261ea1 --- /dev/null +++ b/types/react-splitter-layout/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "jsx": "react", + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-splitter-layout-tests.tsx" + ] +} diff --git a/types/react-splitter-layout/tslint.json b/types/react-splitter-layout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-splitter-layout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3667c06d4542fdc415e5b43accf66c5a44cde4d6 Mon Sep 17 00:00:00 2001 From: Markus Lasermann Date: Fri, 23 Nov 2018 10:05:15 +0100 Subject: [PATCH 013/155] travis build could not parse version --- types/react-splitter-layout/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-splitter-layout/index.d.ts b/types/react-splitter-layout/index.d.ts index ec25b5fe1a..4ee438e983 100644 --- a/types/react-splitter-layout/index.d.ts +++ b/types/react-splitter-layout/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zesik/react-splitter-layout#readme // Definitions by: Markus Lasermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.1.6 +// TypeScript Version: 2.8 import * as React from "react"; From 63e3bac336f8fcccf25224f77202a6a88f5e041c Mon Sep 17 00:00:00 2001 From: Markus Lasermann Date: Fri, 23 Nov 2018 10:33:36 +0100 Subject: [PATCH 014/155] tslint --- types/react-splitter-layout/index.d.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/types/react-splitter-layout/index.d.ts b/types/react-splitter-layout/index.d.ts index 4ee438e983..29273e87ef 100644 --- a/types/react-splitter-layout/index.d.ts +++ b/types/react-splitter-layout/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for react-splitter-layout v3.0.1 -// Project: https://github.com/zesik/react-splitter-layout#readme -// Definitions by: Markus Lasermann +// Type definitions for react-splitter-layout 3.0 +// Project: https://github.com/zesik/react-splitter-layout +// Definitions by: Markus Lasermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -export default SplitterLayout; - -declare class SplitterLayout extends React.PureComponent { +export default class SplitterLayout extends React.PureComponent { } -type TPrimaryIndex = 0|1; +export type TPrimaryIndex = 0|1; export interface SplitterLayoutProps { /** @@ -97,4 +95,3 @@ export interface SplitterLayoutProps { */ onSecondaryPaneSizeChange?: (value: number) => void; } - From e547598a4f1c96bf1bff1774d0fc173b977ecb8d Mon Sep 17 00:00:00 2001 From: Markus Lasermann Date: Fri, 23 Nov 2018 11:34:42 +0100 Subject: [PATCH 015/155] fix tests --- types/react-splitter-layout/react-splitter-layout-tests.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-splitter-layout/react-splitter-layout-tests.tsx b/types/react-splitter-layout/react-splitter-layout-tests.tsx index 1f97db7077..fa9860a2b7 100644 --- a/types/react-splitter-layout/react-splitter-layout-tests.tsx +++ b/types/react-splitter-layout/react-splitter-layout-tests.tsx @@ -1,11 +1,11 @@ import * as React from "react"; -import SplitterLayout, {SplitterLayoutProps} from "react-splitter-layout"; +import SplitterLayout, { SplitterLayoutProps } from "react-splitter-layout"; -export class SplitterLayoutTest extends React.PureComponent<{}> { +export class SplitterLayoutTest extends React.PureComponent { render(): JSX.Element { const props: SplitterLayoutProps = { percentage: true, - secondaryInitialSize: 30, + secondaryInitialSize: 40, }; return ( From f03ea514f73de0a92337a3ccfabf18559ff6a432 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 21 Nov 2018 16:49:40 +0100 Subject: [PATCH 016/155] Update types for ltx --- types/ltx/index.d.ts | 26 +++--- types/ltx/lib/Element.d.ts | 97 ++++++++++---------- types/ltx/lib/Parser.d.ts | 14 ++- types/ltx/lib/clone.d.ts | 4 +- types/ltx/lib/createElement.d.ts | 8 +- types/ltx/lib/equal.d.ts | 10 ++- types/ltx/lib/escape.d.ts | 8 +- types/ltx/lib/is.d.ts | 8 +- types/ltx/lib/parse.d.ts | 5 +- types/ltx/lib/stringify.d.ts | 4 +- types/ltx/lib/tag.d.ts | 4 +- types/ltx/lib/tagString.d.ts | 2 +- types/ltx/ltx-tests.ts | 148 ++++++++++++++++++++++++++++--- types/ltx/tslint.json | 8 +- 14 files changed, 250 insertions(+), 96 deletions(-) diff --git a/types/ltx/index.d.ts b/types/ltx/index.d.ts index 33311a3175..1c313c5541 100644 --- a/types/ltx/index.d.ts +++ b/types/ltx/index.d.ts @@ -1,17 +1,17 @@ -// Type definitions for ltx 2.6 +// Type definitions for ltx 2.8 // Project: github.com/node-xmpp/ltx/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -export {Element } from './lib/Element'; -export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; -export {isNode, isElement, isText} from './lib/is'; -export {clone} from './lib/clone'; -export {createElement} from './lib/createElement'; -export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; -export {Parser} from './lib/Parser'; -export {parse} from './lib/parse'; -export {tag} from './lib/tag'; -export {tagString} from './lib/tagString'; -export {stringify} from './lib/stringify'; +export * from './lib/Element'; +export * from './lib/equal'; +export * from './lib/is'; +export * from './lib/clone'; +export * from './lib/createElement'; +export * from './lib/escape'; +export * from './lib/Parser'; +export * from './lib/parse'; +export * from './lib/tag'; +export * from './lib/tagString'; +export * from './lib/stringify'; diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index 203eaa93b6..7f0d3de62e 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -1,21 +1,26 @@ +import { clone } from './clone'; + +export type Node = Element | TextNode; +export type TextNode = string | number; + /** * Element * * Attributes are in the element.attrs object. Children is a list of * either other Elements or Strings for text content. - **/ -export declare class Element { + */ +export class Element { name: string; - parent: Element; + parent: Element | null; children: Element[]; - attrs: any; + attrs: { [attrName: string]: any }; - constructor(name: string, attrs?: any); + constructor(name: string, attrs?: string | { [attrName: string]: any }); /** * if (element.is('message', 'jabber:client')) ... - **/ - is(name: string, xmlns?: any): boolean; + */ + is(name: string, xmlns?: string): boolean; /** * without prefix. @@ -24,50 +29,44 @@ export declare class Element { /** * retrieves the namespace of the current element, upwards recursively - **/ - getNS(): any; + */ + getNS(): string | undefined; /** * find the namespace to the given prefix, upwards recursively - **/ - findNS(prefix: string): any; + */ + findNS(prefix: string): string | undefined; /** * Recursiverly gets all xmlns defined, in the form of {url:prefix} - **/ - getXmlns(): any; + */ + getXmlns(): { [key: string]: string }; - setAttrs(attrs: any): void; + setAttrs(attrs: string | { [attrName: string]: any }): void; /** - * xmlns can be null, returns the matching attribute. - **/ - getAttr(name: string, xmlns?: any): any; + * returns the matching attribute. + */ + getAttr(name: string, xmlns?: string): any; - /** - * xmlns can be null - **/ - getChild(name: string, xmlns?: any): Element; + getChild(name: string, xmlns?: string): Element | undefined; - /** - * xmlns can be null - **/ - getChildren(name: string, xmlns?: any): Element[]; + getChildren(name: string, xmlns?: string): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + getChildByAttr( + attr: string, + val: any, + xmlns?: string, + recursive?: boolean + ): Element | undefined; + getChildrenByAttr(attr: string, val: any, xmlns?: string, recursive?: boolean): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + getChildrenByFilter(filter: (child: Node) => boolean, recursive?: boolean): Element[]; getText(): string; - getChildText(name: string, xmlns?: any): string; + getChildText(name: string, xmlns?: string): string | null; /** * Return all direct descendents that are Elements. @@ -77,37 +76,39 @@ export declare class Element { getChildElements(): Element[]; /** returns uppermost parent */ - root(): Element; + root(): Element | this; - tree(): Element; + tree(): Element | this; /** just parent or itself */ - up(): Element; + up(): Element | this; /** create child node and return it */ - c(name: string, attrs?: any): Element; + c(name: string, attrs?: { [key: string]: any }): Element; + + cnode(child: T): T; /** add text node and return element */ - t(text: string): Element; + t(text: TextNode): this; /** * Either: * el.remove(childEl) * el.remove('author', 'urn:...') */ - remove(el: Element, xmlns?: any): Element; + remove(el: Element | string, xmlns?: string): this; - clone(): Element; + clone: typeof clone; - text(val: string): string; + text(val?: string): string; - attr(attr: any, val: any): any; + attr(attr: string, val?: any): any; toString(): string; - toJSON(): any; + toJSON(): ElementJson; - write(writer: any): void; + write(writer: (part: string) => void): void; nameEquals(el: Element): boolean; @@ -117,3 +118,9 @@ export declare class Element { equals(el: Element): boolean; } + +export interface ElementJson { + name: string; + attrs: { [attrName: string]: any }; + children: Array; +} diff --git a/types/ltx/lib/Parser.d.ts b/types/ltx/lib/Parser.d.ts index 083e3ace66..463029286f 100644 --- a/types/ltx/lib/Parser.d.ts +++ b/types/ltx/lib/Parser.d.ts @@ -1,5 +1,15 @@ /// import { EventEmitter } from 'events'; -export declare class Parser extends EventEmitter { - constructor(options?: any); +import { Element } from './Element'; + +export class Parser extends EventEmitter { + constructor(options?: ParserOptions); + + write(data: string): void; + end(data: string): void; +} + +export interface ParserOptions { + Parser?: typeof Parser; + Element?: typeof Element; } diff --git a/types/ltx/lib/clone.d.ts b/types/ltx/lib/clone.d.ts index 41193a3f40..15369e00d5 100644 --- a/types/ltx/lib/clone.d.ts +++ b/types/ltx/lib/clone.d.ts @@ -1 +1,3 @@ -export declare function clone(el: any): any; +import { Element } from './Element'; + +export function clone(el: T): T; diff --git a/types/ltx/lib/createElement.d.ts b/types/ltx/lib/createElement.d.ts index c372f11150..21527ae1b6 100644 --- a/types/ltx/lib/createElement.d.ts +++ b/types/ltx/lib/createElement.d.ts @@ -1,2 +1,6 @@ -import { Element } from './Element'; -export declare function createElement(name: string, attrs: any): Element; +import { Element, Node } from './Element'; +export function createElement( + name: string, + attrs?: string | { [attrName: string]: any }, + ...children: Node[] +): Element; diff --git a/types/ltx/lib/equal.d.ts b/types/ltx/lib/equal.d.ts index 520555e098..f7548c526b 100644 --- a/types/ltx/lib/equal.d.ts +++ b/types/ltx/lib/equal.d.ts @@ -1,4 +1,6 @@ -export declare function nameEqual(a: any, b: any): boolean; -export declare function attrsEqual(a: any, b: any): boolean; -export declare function childrenEqual(a: any, b: any): boolean; -export declare function equal(a: any, b: any): boolean; +import { Element } from './Element'; + +export function nameEqual(a: Element, b: Element): boolean; +export function attrsEqual(a: Element, b: Element): boolean; +export function childrenEqual(a: Element, b: Element): boolean; +export function equal(a: Element, b: Element): boolean; diff --git a/types/ltx/lib/escape.d.ts b/types/ltx/lib/escape.d.ts index 4bc45c223a..d390e860ed 100644 --- a/types/ltx/lib/escape.d.ts +++ b/types/ltx/lib/escape.d.ts @@ -1,4 +1,4 @@ -export declare function escapeXML(s: string): string; -export declare function unescapeXML(s: string): string; -export declare function escapeXMLText(s: string): string; -export declare function unescapeXMLText(s: string): string; +export function escapeXML(s: string): string; +export function unescapeXML(s: string): string; +export function escapeXMLText(s: string): string; +export function unescapeXMLText(s: string): string; diff --git a/types/ltx/lib/is.d.ts b/types/ltx/lib/is.d.ts index 6515d23f80..e62d919267 100644 --- a/types/ltx/lib/is.d.ts +++ b/types/ltx/lib/is.d.ts @@ -1,3 +1,5 @@ -export declare function isNode(el: any): boolean; -export declare function isElement(el: any): boolean; -export declare function isText(el: any): boolean; +import { Element, Node } from './Element'; + +export function isNode(el: any): el is Node; +export function isElement(el: any): el is Element; +export function isText(el: any): el is string; diff --git a/types/ltx/lib/parse.d.ts b/types/ltx/lib/parse.d.ts index cc4073113a..0e0a9b17cb 100644 --- a/types/ltx/lib/parse.d.ts +++ b/types/ltx/lib/parse.d.ts @@ -1 +1,4 @@ -export declare function parse(data: any, options?: any): any; +import { ParserOptions, Parser } from './Parser'; +import { Element } from './Element'; + +export function parse(data: string, options?: ParserOptions | Parser): Element; diff --git a/types/ltx/lib/stringify.d.ts b/types/ltx/lib/stringify.d.ts index 770f7d324f..9913f2318c 100644 --- a/types/ltx/lib/stringify.d.ts +++ b/types/ltx/lib/stringify.d.ts @@ -1 +1,3 @@ -export declare function stringify(el: any, indent: any, level: any): string; +import { Element } from './Element'; + +export function stringify(el: Element, indent?: number, level?: number): string; diff --git a/types/ltx/lib/tag.d.ts b/types/ltx/lib/tag.d.ts index 8bbcb6fe7b..11a9784bf0 100644 --- a/types/ltx/lib/tag.d.ts +++ b/types/ltx/lib/tag.d.ts @@ -1 +1,3 @@ -export declare function tag(d: any): any; +import { Element } from './Element'; + +export function tag(literals: string[], ...substitutions: string[]): Element; diff --git a/types/ltx/lib/tagString.d.ts b/types/ltx/lib/tagString.d.ts index 44036ce037..619ccbdb23 100644 --- a/types/ltx/lib/tagString.d.ts +++ b/types/ltx/lib/tagString.d.ts @@ -1 +1 @@ -export declare function tagString(d: any): string; +export function tagString(literals: string[], ...substitutions: string[]): string; diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 522b7673c8..a7342ef54b 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -1,21 +1,147 @@ import * as ltx from 'ltx'; -ltx.parse(''); +let el: ltx.Element = null as any; +let maybeEl: ltx.Element | undefined = null as any; +let els: ltx.Element[] = []; +let bool: boolean; +const any: any = null; +let str: string = null as any; -const getChildTextElement = ltx.parse('body text') as ltx.Element; -if (getChildTextElement.getChildText('child') !== 'body text') { - throw new Error("body does not match"); +el = ltx.clone(el); + +bool = ltx.nameEqual(el, el); +bool = ltx.attrsEqual(el, el); +bool = ltx.childrenEqual(el, el); +bool = ltx.equal(el, el); + +el = ltx.createElement('el'); +el = ltx.createElement('el', 'xml'); +el = ltx.createElement('el', { foo: 'bar' }); +el = ltx.createElement('el', { foo: 'bar' }, el); +el = ltx.createElement('el', { foo: 'bar' }, 'hi'); + +if (ltx.isNode(any)) { + // $ExpectType Node + any; +} +if (ltx.isElement(any)) { + // $ExpectType Element + any; +} +if (ltx.isText(any)) { + // $ExpectType string + any; } -const p = new ltx.Parser(); +str = ltx.escapeXML(str); +str = ltx.unescapeXML(str); +str = ltx.escapeXMLText(str); +str = ltx.unescapeXMLText(str); + +el = ltx.parse(''); +el = ltx.parse('', (null as any) as ltx.Parser); +el = ltx.parse('', { Parser: (null as any) as typeof ltx.Parser }); +el = ltx.parse('', { Element: (null as any) as typeof ltx.Element }); + +el = ltx.tag(['document'], 'foo'); +str = ltx.tagString(['document'], 'foo'); + +str = ltx.stringify(el); +str = ltx.stringify(el, 1); +str = ltx.stringify(el, 1, 1); + +const getChildTextElement = ltx.parse('body text'); +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error('body does not match'); +} + +let p: ltx.Parser; +p = new ltx.Parser(); +p = new ltx.Parser({ Parser: (null as any) as typeof ltx.Parser }); +p = new ltx.Parser({ Element: (null as any) as typeof ltx.Element }); p.on('tree', (ignored: any) => {}); - p.on('error', (ignored: any) => {}); -const el = new ltx.Element('root').c('children'); -el.c('child', {age: 5}).t('Hello').up() - .c('child', {age: 7}).t('Hello').up() - .c('child', {age: 99}).t('Hello').up(); +el = new ltx.Element('root').c('children'); -el.root().toString(); +bool = el.is('el'); +bool = el.is('el', 'ns'); +str = el.getName(); +let s: string | undefined = el.getNS(); +s = el.findNS('ns'); +const xmlns: { [key: string]: string } = el.getXmlns(); +el.setAttrs('ho'); +el.setAttrs({ my: 'attr' }); +el.getAttr('ho'); +el.getAttr('ho', 'ns'); +maybeEl = el.getChild('el'); +maybeEl = el.getChild('el', 'ns'); +els = el.getChildren('el'); +els = el.getChildren('el', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByAttr('my', 'attr'); +els = el.getChildrenByAttr('my', 'attr', 'ns'); +els = el.getChildrenByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}, true); +str = el.getText(); +let maybeS: string | null = el.getChildText('hi'); +maybeS = el.getChildText('hi', 'ns'); +els = el.getChildElements(); + +class MyEl extends ltx.Element { + foo: 'bar'; +} +let myEl = new MyEl('el'); + +// $ExpectType Element | MyEl +myEl.root(); +// $ExpectType Element | MyEl +myEl.tree(); +// $ExpectType Element | MyEl +myEl.up(); + +el = el.c('hi'); +el = el.c('hi', { my: 'attr' }); +myEl = myEl.cnode(myEl); +myEl = myEl.t('hi'); +myEl = myEl.t(1); +myEl = myEl.remove(el); +myEl = myEl.remove('el'); +myEl = myEl.remove('el', 'ns'); +myEl = myEl.clone(myEl); +str = el.text(); +str = el.text('val'); +el.attr('my'); +el.attr('my', 'attr'); +str = el.toString(); +const json: ltx.ElementJson = el.toJSON(); +el.write(part => { + // $ExpectType string + part; +}); +bool = el.nameEquals(el); +bool = el.attrsEquals(el); +bool = el.childrenEquals(el); +bool = el.equals(el); + +el.c('child', { age: 5 }) + .t('Hello') + .up() + .c('child', { age: 7 }) + .t('Hello') + .up() + .c('child', { age: 99 }) + .t('Hello') + .up(); diff --git a/types/ltx/tslint.json b/types/ltx/tslint.json index 5bb1e8735d..f93cf8562a 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1,9 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // All are TODOs - "jsdoc-format": false, - "no-consecutive-blank-lines": false, - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json" } From 16033f3b89831cdd6f23c1236ed8a0b741ca522e Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 19 Nov 2018 21:43:50 +0100 Subject: [PATCH 017/155] Correct return types for p-defer --- types/p-defer/index.d.ts | 17 +++++++++-------- types/p-defer/p-defer-tests.ts | 12 ++++++------ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/types/p-defer/index.d.ts b/types/p-defer/index.d.ts index 7eff607e7d..8386706d89 100644 --- a/types/p-defer/index.d.ts +++ b/types/p-defer/index.d.ts @@ -1,16 +1,17 @@ // Type definitions for p-defer 1.0 // Project: https://github.com/sindresorhus/p-defer // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace pDefer { - interface DeferredPromise { - resolve(value?: U | PromiseLike): Promise; - reject(reason: any): Promise; - promise: Promise; - } -} +export = pDefer; declare function pDefer(): pDefer.DeferredPromise; -export = pDefer; +declare namespace pDefer { + interface DeferredPromise { + resolve(value?: T | PromiseLike): void; + reject(reason: any): void; + promise: Promise; + } +} diff --git a/types/p-defer/p-defer-tests.ts b/types/p-defer/p-defer-tests.ts index 9ea4647620..f61bce624b 100644 --- a/types/p-defer/p-defer-tests.ts +++ b/types/p-defer/p-defer-tests.ts @@ -1,13 +1,13 @@ import pDefer = require('p-defer'); -function delay(deferred: pDefer.DeferredPromise, ms: number) { +function delay(deferred: pDefer.DeferredPromise, ms: number) { setTimeout(deferred.resolve, ms, '🦄'); return deferred.promise; } -let s: string; -async function f() { s = await delay(pDefer(), 100); } +const s: Promise = delay(pDefer(), 100); -async function u() { - const u: Promise = pDefer().resolve(); -} +// $ExpectType void +pDefer().resolve(); +// $ExpectType void +pDefer().reject('oh no'); From 64df3bfb11d384c4d404c71e05ff47aea9b7e8cb Mon Sep 17 00:00:00 2001 From: Alan Plum Date: Fri, 23 Nov 2018 17:53:22 +0100 Subject: [PATCH 018/155] Add mcrypt@0.1 --- types/mcrypt/index.d.ts | 31 ++++++++++++++++++++++ types/mcrypt/mcrypt-tests.ts | 51 ++++++++++++++++++++++++++++++++++++ types/mcrypt/tsconfig.json | 16 +++++++++++ types/mcrypt/tslint.json | 1 + 4 files changed, 99 insertions(+) create mode 100644 types/mcrypt/index.d.ts create mode 100644 types/mcrypt/mcrypt-tests.ts create mode 100644 types/mcrypt/tsconfig.json create mode 100644 types/mcrypt/tslint.json diff --git a/types/mcrypt/index.d.ts b/types/mcrypt/index.d.ts new file mode 100644 index 0000000000..945cb88e59 --- /dev/null +++ b/types/mcrypt/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for mcrypt 0.1 +// Project: https://github.com/tugrul/node-mcrypt +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export function getAlgorithmNames(): string[]; +export function getModeNames(): string[]; + +export class MCrypt { + constructor(algorithm: string, mode: string); + open(key: string | Buffer, iv?: string | Buffer): void; + encrypt(plaintext: string | Buffer): Buffer; + decrypt(ciphertext: Buffer): Buffer; + generateIv(): Buffer; + validateKeySize(validate: boolean): void; + validateIvSize(validate: boolean): void; + selfTest(): boolean; + isBlockAlgorithmMode(): boolean; + isBlockAlgorithm(): boolean; + isBlockMode(): boolean; + getBlockSize(): number; + getKeySize(): number; + getSupportedKeySizes(): number[]; + getIvSize(): number; + hasIv(): boolean; + getAlgorithmName(): string; + getModeName(): string; +} diff --git a/types/mcrypt/mcrypt-tests.ts b/types/mcrypt/mcrypt-tests.ts new file mode 100644 index 0000000000..66614e08e3 --- /dev/null +++ b/types/mcrypt/mcrypt-tests.ts @@ -0,0 +1,51 @@ +import { getAlgorithmNames, getModeNames, MCrypt } from "mcrypt"; + +let plaintext: Buffer; +let ciphertext: Buffer; + +for (const algo of getAlgorithmNames()) { + console.log(algo.toUpperCase()); +} +for (const mode of getModeNames()) { + console.log(mode.toUpperCase()); +} + +const desEcb = new MCrypt("des", "ecb"); +desEcb.open("madepass"); + +ciphertext = desEcb.encrypt("too many secrets"); +console.log(ciphertext.toString("base64")); + +plaintext = desEcb.decrypt(ciphertext); +console.log(plaintext.toString()); + +const blowfishCfb = new MCrypt("blowfish", "cfb"); +const iv = blowfishCfb.generateIv(); +blowfishCfb.open("somekey", iv); +ciphertext = blowfishCfb.encrypt("sometext"); +console.log(Buffer.concat([iv, ciphertext]).toString("base64")); + +const bfEcb = new MCrypt("blowfish", "ecb"); +bfEcb.validateKeySize(false); +bfEcb.open("typeconfig.sys^_-"); + +const rjCbc = new MCrypt("rijndael-256", "cbc"); +rjCbc.validateIvSize(false); +rjCbc.open("$verysec$retkey$", "foobar"); + +console.log(blowfishCfb.getBlockSize() * 8); +console.log(blowfishCfb.getKeySize() * 8); +console.log(blowfishCfb.getSupportedKeySizes().map(v => v * 8)); +console.log(blowfishCfb.getIvSize() * 8); +console.log(blowfishCfb.getAlgorithmName().toUpperCase()); +console.log(blowfishCfb.getModeName().toUpperCase()); + +function assertBool(value: boolean) { + return value; +} + +assertBool(blowfishCfb.selfTest()); +assertBool(blowfishCfb.isBlockAlgorithmMode()); +assertBool(blowfishCfb.isBlockAlgorithm()); +assertBool(blowfishCfb.isBlockMode()); +assertBool(blowfishCfb.hasIv()); diff --git a/types/mcrypt/tsconfig.json b/types/mcrypt/tsconfig.json new file mode 100644 index 0000000000..1bb1454ce5 --- /dev/null +++ b/types/mcrypt/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mcrypt-tests.ts"] +} diff --git a/types/mcrypt/tslint.json b/types/mcrypt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mcrypt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3df7d2836e432e949b26de57741265aad9cf1e8d Mon Sep 17 00:00:00 2001 From: Alan Plum Date: Fri, 23 Nov 2018 23:45:29 +0100 Subject: [PATCH 019/155] Add promised-ldap@0.3 --- types/promised-ldap/index.d.ts | 95 ++++++++++++++++++++++ types/promised-ldap/promised-ldap-tests.ts | 39 +++++++++ types/promised-ldap/tsconfig.json | 16 ++++ types/promised-ldap/tslint.json | 1 + 4 files changed, 151 insertions(+) create mode 100644 types/promised-ldap/index.d.ts create mode 100644 types/promised-ldap/promised-ldap-tests.ts create mode 100644 types/promised-ldap/tsconfig.json create mode 100644 types/promised-ldap/tslint.json diff --git a/types/promised-ldap/index.d.ts b/types/promised-ldap/index.d.ts new file mode 100644 index 0000000000..53f215b2b8 --- /dev/null +++ b/types/promised-ldap/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for promised-ldap 0.3 +// Project: https://github.com/stewartml/promised-ldap#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { EventEmitter } from "events"; +import * as ldap from "ldapjs"; + +declare class Client extends EventEmitter { + constructor({ url }: { url: string }); + + search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[] + ): Promise<{ + entries: any[]; + references: any[]; + }>; + + authenticate(base: string, dn: string, password: string): Promise; + authenticateUser( + base: string, + dn: string, + password: string + ): Promise<{ name: string; email: string; groups: string[] } | null>; + + bind( + dn: string, + password: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + add( + name: string, + entry: object, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + compare( + name: string, + attr: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + del(name: string, controls?: ldap.Control | ldap.Control[]): Promise; + + exop( + name: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modify( + name: string, + change: ldap.Change | ldap.Change[], + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modifyDN( + name: string, + newName: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + _search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + _search( + base: string, + options: ldap.SearchOptions, + _bypass: boolean + ): Promise; + + starttls( + options: object, + controls: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + + unbind(): Promise; + + destroy(err?: any): void; +} + +declare namespace Client { + type SearchOptions = ldap.SearchOptions; +} + +export = Client; diff --git a/types/promised-ldap/promised-ldap-tests.ts b/types/promised-ldap/promised-ldap-tests.ts new file mode 100644 index 0000000000..b61f7ef6fc --- /dev/null +++ b/types/promised-ldap/promised-ldap-tests.ts @@ -0,0 +1,39 @@ +import ldap = require("promised-ldap"); +import ldapjs = require("ldapjs"); + +const client = new ldap({ + url: "ldap://127.0.0.1:1389" +}); + +client.authenticate("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.authenticateUser("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.bind("cn=root", "secret").catch((err: Error) => { + console.error(err); +}); + +const opts: ldap.SearchOptions = { + filter: "(&(l=Seattle)(email=*@foo.com))", + scope: "sub", + attributes: ["dn", "sn", "cn"] +}; + +client._search("o=example", opts).then((res: NodeJS.EventEmitter) => { + console.log(res); +}); + +const change = new ldapjs.Change({ + operation: "add", + modification: { + pets: ["cat", "dog"] + } +}); + +client.modify("cn=foo, o=example", change).catch((err: Error) => { + console.error(err); +}); diff --git a/types/promised-ldap/tsconfig.json b/types/promised-ldap/tsconfig.json new file mode 100644 index 0000000000..89b60715eb --- /dev/null +++ b/types/promised-ldap/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "promised-ldap-tests.ts"] +} diff --git a/types/promised-ldap/tslint.json b/types/promised-ldap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promised-ldap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1cef81059eccb564654a9942955300c2073bb3f3 Mon Sep 17 00:00:00 2001 From: Alan Plum Date: Sat, 24 Nov 2018 01:45:43 +0100 Subject: [PATCH 020/155] Update index.d.ts --- types/promised-ldap/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/promised-ldap/index.d.ts b/types/promised-ldap/index.d.ts index 53f215b2b8..8b0182bea6 100644 --- a/types/promised-ldap/index.d.ts +++ b/types/promised-ldap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for promised-ldap 0.3 -// Project: https://github.com/stewartml/promised-ldap#readme -// Definitions by: My Self +// Project: https://github.com/stewartml/promised-ldap +// Definitions by: Alan Plum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 From a169bc5dda5c595439062712c4d0429b4def512d Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Sat, 24 Nov 2018 14:26:28 +0000 Subject: [PATCH 021/155] [cached-path-relative] Add documentation to new definition --- types/cached-path-relative/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/cached-path-relative/index.d.ts b/types/cached-path-relative/index.d.ts index 56076870bc..b2af5ea81c 100644 --- a/types/cached-path-relative/index.d.ts +++ b/types/cached-path-relative/index.d.ts @@ -3,6 +3,11 @@ // Definitions by: TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Memoize the results of the path.relative function. path.relative can be an expensive operation + * if it happens a lot, and its results shouldn't change for the same arguments. + * Use it just like your normal path.relative, but it's memoized. + */ declare function cachedPathRelative(from: string, to: string): string; export = cachedPathRelative; From 02da4b8731282cb35ed274cc337fcc64fd53f619 Mon Sep 17 00:00:00 2001 From: izmhr Date: Sun, 25 Nov 2018 20:40:27 +0900 Subject: [PATCH 022/155] Completely new definitions for SkyWay@1.1.17 and TypeScript@3.0 --- types/skyway/index.d.ts | 327 ++++++++++++++++------------------- types/skyway/skyway-tests.ts | 51 +++--- 2 files changed, 171 insertions(+), 207 deletions(-) diff --git a/types/skyway/index.d.ts b/types/skyway/index.d.ts index eb73937178..8cdbec4a8e 100644 --- a/types/skyway/index.d.ts +++ b/types/skyway/index.d.ts @@ -1,185 +1,154 @@ -// Type definitions for SkyWay -// Project: http://nttcom.github.io/skyway/ +// Type definitions for SkyWay@1.1.17 +// Project: https://github.com/skyway/skyway-js-sdk +// Based on Documentation for skyway-js-doc: https://github.com/skyway/skyway-js-sdk-doc // Definitions by: Toshiya Nakakura +// Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 -/// - -declare namespace PeerJs{ - interface PeerJSOption{ - key?: string; - host?: string; - port?: number; - path?: string; - secure?: boolean; - turn?: boolean; - config?: RTCPeerConnectionConfig; - debug?: number; - } - - interface PeerConnectOption{ - label?: string; - metadata?: any; - serialization?: string; - reliable?: boolean; - } - - interface DataConnection{ - send(data: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'data', cb: (data: any)=>void): void; - on(event: 'open', cb: ()=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - bufferSize: number; - dataChannel: RTCDataChannel; - label: string; - metadata: any; - open: boolean; - peerConnection: any; - peer: string; - reliable: boolean; - serialization: string; - type: string; - } - - interface MediaConnection{ - answer(stream?: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'stream', cb: (stream: any)=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - open: boolean; - metadata: any; - peer: string; - type: string; - } - - interface utilSupportsObj { - audioVideo: boolean; - data: boolean; - binary: boolean; - reliable: boolean; - } - - interface util{ - browser: string; - supports: utilSupportsObj; - } - - export interface Peer{ - /** - * - * @param id The brokering ID of the remote peer (their peer.id). - * @param options for specifying details about Peer Connection - */ - connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; - /** - * Connects to the remote peer specified by id and returns a data connection. - * @param id The brokering ID of the remote peer (their peer.id). - * @param stream The caller's media stream - */ - call(id: string, stream: any): PeerJs.MediaConnection; - /** - * Calls the remote peer specified by id and returns a media connection. - * @param event Event name - * @param cb Callback Function - */ - on(event: string, cb: ()=>void): void; - /** - * Emitted when a connection to the PeerServer is established. - * @param event Event name - * @param cb id is the brokering ID of the peer - */ - on(event: 'open', cb: (id: string)=>void): void; - /** - * Emitted when a new data connection is established from a remote peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; - /** - * Emitted when a remote peer attempts to call you. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; - /** - * Emitted when the peer is destroyed and can no longer accept or create any new connections. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'close', cb: ()=>void): void; - /** - * Emitted when the peer is disconnected from the signalling server - * @param event Event name - * @param cb Callback Function - */ - on(event: 'disconnected', cb: ()=>void): void; - /** - * Errors on the peer are almost always fatal and will destroy the peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'error', cb: (err: any)=>void): void; - /** - * Remove event listeners.(EventEmitter3) - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Boolean} once Only remove once listeners. - */ - off(event: string, fn: Function, once?: boolean): void; - /** - * Close the connection to the server, leaving all existing data and media connections intact. - */ - disconnect(): void; - /** - * Close the connection to the server and terminate all existing connections. - */ - destroy(): void; - /** - * Get a list of available peer IDs - * @param callback - */ - listAllPeers(callback: (peerIds: Array)=>void): void; - - /** - * The brokering ID of this peer - */ - id: string; - /** - * A hash of all connections associated with this peer, keyed by the remote peer's ID. - */ - connections: any; - /** - * false if there is an active connection to the PeerServer. - */ - disconnected: boolean; - /** - * true if this peer and all of its connections can no longer be used. - */ - destroyed: boolean; - } +interface Options { + key: string; + debug?: number; + turn?: boolean; + credential?: Credential; + config?: RTCConfiguration; } -declare var Peer: { - prototype: RTCIceServer; - /** - * A peer can connect to other peers and listen for connections. - * @param id Other peers can connect to this peer using the provided ID. - * If no ID is given, one will be generated by the brokering server. - * @param options for specifying details about PeerServer - */ - new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; +interface Credential { + timestamp?: number; + ttl?: number; + authToken?: string; +} - /** - * A peer can connect to other peers and listen for connections. - * @param options for specifying details about PeerServer - */ - new (options: PeerJs.PeerJSOption): PeerJs.Peer; -}; +interface CallOptions { + metadata?: any; + videoBandWidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; + label?: string; +} + +interface ConnectOptions { + metadata?: any; + serialization?: string; + dcInit?: RTCDataChannelInit; + label?: string; +} + +interface RoomOptions { + mode?: string; + stream?: MediaStream; + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; +} + +interface AnswerOptions { + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; +} + +declare class Peer { + constructor(id: string, options: Options); + constructor(options: Options); + + connections: any; + id: string; + open: boolean; + rooms: any; + + call(peerId: string, stream?: MediaStream, options?: CallOptions): MediaConnection | undefined; + connect(peerId: string, options?: ConnectOptions): DataConnection | undefined; + destroy(): undefined; + disconnect(): undefined; + joinRoom(roomName: string, roomOptions?: RoomOptions): SFURoom | MeshRoom | undefined | null; + listAllPeers(cb: (peerIds: Array) => void): void; + updateCredential(newCredential: Credential): undefined; + + on(event: string, cb: (ret: any) => void): void; + on(event: 'open', cb: (id: string) => void): void; + on(event: 'call', cb: (call: MediaConnection) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'connection', cb: (connection: DataConnection) => void): void; + on(event: 'disconnected', cb: (id: string) => void): void; + on(event: 'error', cb: (err: any) => void): void; +} + +declare class MediaConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + answer(stream: MediaStream, options?: AnswerOptions): undefined; + close(): void | undefined; + replaceStream(stream: MediaStream): undefined; + + on(event: string, cb: () => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (reamoteStream: MediaStream) => void): void; +} + +declare class DataConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + send(data: any): void; + close(): void | undefined; + + on(event: string, cb: () => void): void; + on(event: 'data', cb: (data: any) => void): void; + on(event: 'close', cb: () => void): void; +} + +interface DataObject { + src: string; + data: any; +} + +declare class MeshRoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} + +declare class SFURoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} diff --git a/types/skyway/skyway-tests.ts b/types/skyway/skyway-tests.ts index 2731192f75..46ee924bcb 100644 --- a/types/skyway/skyway-tests.ts +++ b/types/skyway/skyway-tests.ts @@ -1,44 +1,39 @@ -var peerByOption: PeerJs.Peer = new Peer({ +/// + +const peerByOption: Peer = new Peer({ key: 'peerKey', - debug: 3, + debug: 3 }); -peerByOption.listAllPeers(function(items){ - for(var i in items){ - console.log(decodeURI(items[i])); +peerByOption.listAllPeers((items) => { + for (let item in items) { + console.log(decodeURI(items[item])); } }); -var peerById: PeerJs.Peer = new Peer("peerid"); +const peerByIdAndOption: Peer = new Peer('peerid', { + key: 'peerKey', + debug: 3 +}); -var peerByIdAndOption: PeerJs.Peer = new Peer( - "peerId", - { - key: 'peerKey', - debug: 3, - }); - -var id = peerByOption.id; -var connections = peerByOption.connections; -var flag = peerByOption.disconnected; -flag = peerByOption.destroyed; +let id = peerByOption.id; +let connections = peerByOption.connections; peerByOption.disconnect(); peerByOption.destroy(); -var connection = peerById.connect("id", { +let connection = peerByOption.connect("id", { label: 'chat', serialization: 'none', - metadata: {message: 'hi i want to chat with you!'} + metadata: { message: 'hi i want to chat with you!' } }); -var call = peerById.call('callto-id', (window).localStream); +let call = peerByOption.call('callto-id', (window as any).localStream); -var openHandler=()=> console.log("open"); -peerById.on("open", openHandler); -peerById.on("connection", (c)=> console.log("connection")); -peerById.on("call", (media)=> console.log("call")); -peerById.on("close", ()=> console.log("close")); -peerById.on("disconnected", ()=> console.log("disconnected")); -peerById.on("error", (err)=> console.log(err)); -peerById.off("open", openHandler); +let openHandler = () => console.log("open"); +peerByOption.on("open", openHandler); +peerByOption.on("connection", (c) => console.log("connection")); +peerByOption.on("call", (media) => console.log("call")); +peerByOption.on("close", () => console.log("close")); +peerByOption.on("disconnected", () => console.log("disconnected")); +peerByOption.on("error", (err) => console.log(err)); From 0577b97e084594414b2db82616c72e91f04793ea Mon Sep 17 00:00:00 2001 From: izmhr Date: Sun, 25 Nov 2018 21:04:01 +0900 Subject: [PATCH 023/155] checking npm test error --- types/skyway/index.d.ts | 1 - types/skyway/skyway-tests.ts | 2 -- 2 files changed, 3 deletions(-) diff --git a/types/skyway/index.d.ts b/types/skyway/index.d.ts index 8cdbec4a8e..044768a08e 100644 --- a/types/skyway/index.d.ts +++ b/types/skyway/index.d.ts @@ -1,6 +1,5 @@ // Type definitions for SkyWay@1.1.17 // Project: https://github.com/skyway/skyway-js-sdk -// Based on Documentation for skyway-js-doc: https://github.com/skyway/skyway-js-sdk-doc // Definitions by: Toshiya Nakakura // Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/skyway/skyway-tests.ts b/types/skyway/skyway-tests.ts index 46ee924bcb..702a05e709 100644 --- a/types/skyway/skyway-tests.ts +++ b/types/skyway/skyway-tests.ts @@ -1,5 +1,3 @@ -/// - const peerByOption: Peer = new Peer({ key: 'peerKey', debug: 3 From adace47dc209c52a74da1641206e7fbcea7023f7 Mon Sep 17 00:00:00 2001 From: Julian Strecker Date: Sun, 25 Nov 2018 13:38:13 +0100 Subject: [PATCH 024/155] [three,physijs] fix tests to fullfill travis needs. --- types/physijs/test/collisions.ts | 4 ++-- types/physijs/test/vehicle.ts | 4 ++-- types/three/test/css3d/css3d_periodictable.ts | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/types/physijs/test/collisions.ts b/types/physijs/test/collisions.ts index 20493189e0..41f09e351d 100644 --- a/types/physijs/test/collisions.ts +++ b/types/physijs/test/collisions.ts @@ -90,7 +90,7 @@ spawnBox = (function() { var box_geometry = new THREE.BoxGeometry( 4, 4, 4 ), handleCollision = function( collided_with ) { - var target = this; + var target = this as any; target.collisions = 0; switch (++target.collisions) { @@ -168,4 +168,4 @@ render = function() { render_stats.update(); }; -window.onload = initScene; \ No newline at end of file +window.onload = initScene; diff --git a/types/physijs/test/vehicle.ts b/types/physijs/test/vehicle.ts index b8643de3b0..37f32279a8 100644 --- a/types/physijs/test/vehicle.ts +++ b/types/physijs/test/vehicle.ts @@ -186,11 +186,11 @@ initScene = function() { ); } - input = { + input = { power: null, direction: null, steering: 0 - }; + } as any; document.addEventListener('keydown', function( ev ) { switch ( ev.keyCode ) { case 37: // left diff --git a/types/three/test/css3d/css3d_periodictable.ts b/types/three/test/css3d/css3d_periodictable.ts index 5c8cb68614..40a29a1ea5 100644 --- a/types/three/test/css3d/css3d_periodictable.ts +++ b/types/three/test/css3d/css3d_periodictable.ts @@ -181,8 +181,8 @@ // var object = new THREE.Object3D(); - object.position.x = (table[i + 3] * 140) - 1330; - object.position.y = - (table[i + 4] * 180) + 990; + object.position.x = ((table[i + 3] as number) * 140) - 1330; + object.position.y = - ((table[i + 4] as number) * 180) + 990; targets.table.push(object); @@ -354,4 +354,4 @@ renderer.render(scene, camera); } -} \ No newline at end of file +} From 3a4659d36dc86a41af8dfeb17a6d87ad890404b8 Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Sun, 25 Nov 2018 14:31:37 +0100 Subject: [PATCH 025/155] Update to version 3.0.2 --- types/tabtab/index.d.ts | 152 +++++++++++++++++++++++++++------------- 1 file changed, 103 insertions(+), 49 deletions(-) diff --git a/types/tabtab/index.d.ts b/types/tabtab/index.d.ts index eba5a58c3a..05291613b2 100644 --- a/types/tabtab/index.d.ts +++ b/types/tabtab/index.d.ts @@ -1,89 +1,143 @@ -// Type definitions for tabtab 0.0.4 +// Type definitions for tabtab 3.0.2 // Project: https://github.com/mklabs/node-tabtab // Definitions by: Vojtěch Habarta +// Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - +// TypeScript Version: 2.0 /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param cb Get called when a tab-completion command happens. + * Install option + * + * @param name is a name of the cli command + * @param completer Somethings, you want to complete another program that's where the `completer` option might come handy. */ -export declare function complete(name: string, cb: CallBack): void; +export type InstallOption = { + name: string; + completer: string; +}; /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param completer Name of the command to call on completion. - * @param cb Get called when a tab-completion command happens. + * Uninstall option + * + * @param name is a name of the cli command */ -export declare function complete(name: string, completer: string, cb: CallBack): void; +export type UninstallOption = { + name: string; +}; /** - * Simple helper function to know if the script is run in the context of a completion command. + * This type represent object (Json object) */ -export declare function isComplete(): boolean; +export type Json = { + [key: string]: string; +}; /** - * Helper to return the list of short and long options, parsed from the usual --help output of a command (cake/rake -H, vagrant, commander -h, optimist.help(), ...). + * Tabtab environment data that return from {@link parseEnv} method + * + * @param complete A Boolean indicating whether we act in "plumbing mode" or not + * @param words The Number of words in the completed line + * @param point A Number indicating cursor position + * @param line The String input line + * @param partial The String part of line preceding cursor position + * @param last The last String word of the line + * @param lastPartial The last word String of partial + * @param prev The String word preceding last */ -export declare function parseOut(str: string): { shorts: string[]; longs: string[] }; - -/** - * Same purpose as parseOut, but for parsing tasks from an help command (cake/rake -T, vagrant, etc.). - */ -export declare function parseTasks(str: string, prefix: string, reg?: RegExp | string): string[]; - -/** - * Helper to return completion output and log to standard output. - * @param values Array of values to complete against. - * @param data The data object returned by the complete callback, used mainly to filter results accordingly upon the text that is supplied by the user. - * @param prefix A prefix to add to the completion results, useful for options to add dashes (eg. - or --). - */ -export declare function log(values: string[], data: Data, prefix?: string): void; - -interface CallBack { - (error?: Error, data?: Data, text?: string): any; -} - -/** - * Holds interesting values to drive the output of the completion. - */ -interface Data { - +export type TabtabEnv = { /** - * full command being completed + * A Boolean indicating whether we act in "plumbing mode" or not */ - line: string; + complete: boolean; /** - * number of words + * The Number of words in the completed line */ words: number; /** - * cursor position + * A Number indicating cursor position */ point: number; /** - * tabing in the middle of a word: foo bar baz bar foobarrrrrrr + * The String input line + */ + line: string; + + /** + * The String part of line preceding cursor position */ partial: string; /** - * last word of the line + * The last String word of the line */ last: string; /** - * last partial of the line + * The last word String of partial */ lastPartial: string; - /** - * the previous word + * The String word preceding last */ prev: string; -} +}; + +/** + * this is a item to show when completion enable, + * + * @param name usually is a subcommand name or option name + * @param description this is a optional description of the completion + */ +export type CompleteItem = { + name: string; + description?: string; +}; + +export type CompleteItemOrString = string | CompleteItem; + +/** + * Install and enable completion on user system. + * + * @param option install option + * + */ +export function install(option: InstallOption): Promise; + +/** + * Uninstall and remove all completion on user system + * + * @param option uninstall option + */ +export function uninstall(option: UninstallOption): Promise; + +/** + * Public: Main utility to extract information from command line arguments and + * Environment variables, namely COMP args in "plumbing" mode. + * + * @param env environment (usually will be process.env) + * @returns env is a object of completion environment + * + * @example + * const env = tabtab.parseEnv(process.env); + */ +export function parseEnv(env: Json): TabtabEnv; + +/** + * Helper to normalize String and Objects when logging out. + */ +export function completionItem(item: CompleteItemOrString): CompleteItem; + +/** + * Main logging utility to pass completion items. + * This is simply an helper to log to stdout with each item separated by a new + * line. + * + * Bash needs in addition to filter out the args for the completion to work + * (zsh, fish don't need this). + * + * @param args Strings or Objects with name and description property. + */ +export function log(args: string[] | CompleteItem[] | CompleteItemOrString[]): void; From 8b982e49c565d136473bd3f794837e2374b2136a Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Sun, 25 Nov 2018 14:33:34 +0100 Subject: [PATCH 026/155] Update test define file --- types/tabtab/tabtab-tests.ts | 99 +++++++++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 23 deletions(-) diff --git a/types/tabtab/tabtab-tests.ts b/types/tabtab/tabtab-tests.ts index e0187662ff..7f8e5b4b9c 100644 --- a/types/tabtab/tabtab-tests.ts +++ b/types/tabtab/tabtab-tests.ts @@ -1,30 +1,83 @@ - /// -import tabtab = require('tabtab'); -import child_process = require('child_process'); -import string_decoder = require('string_decoder'); +import { install, log, TabtabEnv, uninstall, parseEnv } from "tabtab"; -if (process.argv.slice(2)[0] === 'completion') { - tabtab.complete('pkgname', function(err, data) { - if (err || !data) return; - if (/^--\w?/.test(data.last)) return tabtab.log(['help', 'version'], data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(['n', 'o', 'd', 'e'], data, '-'); - tabtab.log(['list', 'of', 'commands'], data); +const opts = require("minimist")(process.argv.slice(2), { + string: ["foo", "bar"], + boolean: ["help", "version", "loglevel"] +}); - child_process.exec('rake -H', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var parsed = tabtab.parseOut(decoder.write(stdout)); - if (/^--\w?/.test(data.last)) return tabtab.log(parsed.longs, data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(parsed.shorts, data, '-'); +const args = opts._; + +const completion = (env: TabtabEnv) => { + if (!env.complete) return; + + // Write your completions there + + if (env.prev === "foo") { + return log(["is", "this", "the", "real", "life"]); + } + + if (env.prev === "bar") { + return log(["is", "this", "just", "fantasy"]); + } + + if (env.prev === "--loglevel") { + return log(["error", "warn", "info", "notice", "verbose"]); + } + + return log([ + "--help", + "--version", + "--loglevel", + "foo", + "bar", + "install-completion", + "completion", + "someCommand:someCommand is some kind of command with a description", + { + name: "someOtherCommand:hey", + description: 'You must add a description for items with ":" in them' + }, + "anotherOne" + ]); +}; + +const run = (): Promise => { + const cmd = args[0]; + + // Write your CLI there + + // Here we install for the program `tabtab-test` (this file), with + // completer being the same program. Sometimes, you want to complete + // another program that's where the `completer` option might come handy. + if (cmd === "install-completion") { + return install({ + name: "tabtab-test", + completer: "tabtab-test" }); + } - child_process.exec('cake', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var tasks = tabtab.parseTasks(decoder.write(stdout), 'cake'); - tabtab.log(tasks, data); + if (cmd === "uninstall-completion") { + // Here we uninstall for the program `tabtab-test` (this file). + return uninstall({ + name: "tabtab-test" }); - }); -} + } + + // The completion command is added automatically by tabtab when the program + // is completed. + if (cmd === "completion") { + return new Promise(res => { + const env = parseEnv(process.env); + completion(env); + res(); + }); + } + + return new Promise((_, rej) => rej()); +}; + +run().catch(e => { + console.error(e); +}); From 28cec6d7e832384d8e93596e6b723ea179d8d84f Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 25 Nov 2018 15:02:24 +0100 Subject: [PATCH 027/155] Add types for iri --- types/iri/index.d.ts | 89 +++++++++++++++++++++++++++++++++++++++++ types/iri/iri-tests.ts | 43 ++++++++++++++++++++ types/iri/tsconfig.json | 23 +++++++++++ types/iri/tslint.json | 1 + 4 files changed, 156 insertions(+) create mode 100644 types/iri/index.d.ts create mode 100644 types/iri/iri-tests.ts create mode 100644 types/iri/tsconfig.json create mode 100644 types/iri/tslint.json diff --git a/types/iri/index.d.ts b/types/iri/index.d.ts new file mode 100644 index 0000000000..93183bcfad --- /dev/null +++ b/types/iri/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for iri 1.3 +// Project: https://github.com/awwright/node-iri +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class IRI { + /** + * The constructor takes a single argument, a URI or IRI string: + */ + constructor(iri: string); + /** + * Returns UTF-16 IRI + */ + toString(): string; + /** + * Returns the IRI without the fragment component. Useful for dereferencing URLs on a network. + */ + defrag(): IRI; + /** + * IRIs with a fragment are not absolute. + */ + isAbsolute(): boolean; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + toAbsolute(): IRI; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + authority(): string | null; + /** + * Returns the fragment component of the IRI. + */ + fragment(): string | null; + /** + * Returns the hier-part of the IRI, the hierarchial component: Everything between the scheme and query, including leading `//` for the host, if it exists. + */ + hierpart(): string; + /** + * Returns the host component of the URI, either a domain name or string-formatted IP address. Excludes port number and username/password. + */ + host(): string; + /** + * Returns the path component of the hier-part. Does not include the authority/host, query, or fragment. + */ + path(): string; + /** + * Returns the port component of the authority as a string, or `null` if there is no port. + */ + port(): string | null; + /** + * Returns the query component of the IRI including leading "?", or `null` if there is no query component. + */ + query(): string | null; + /** + * Resolve the provided URI/IRI reference against this IRI. + */ + resolveReference(ref: string | IRI): IRI; + /** + * Returns the scheme of the IRI, e.g. "https", "file", or "urn". + */ + scheme(): string | null; + /** + * Returns the username/password component of the IRI. + */ + userinfo(): string | null; + /** + * Returns a URI formatted string with only 7-bit characters. + */ + toURIString(): string; + /** + * Decodes URI-encoded UTF-8 characters and returns a unicode string (Strings in ECMAScript/JavaScript are UTF-16). + */ + toIRIString(): string; + /** + * Returns a new IRI object with URI-encoded UTF-8 characters decoded. + */ + toIRI(): IRI; +} + +/** + * Returns an iri.IRI object with UTF-8 escaped characterd decoded. + */ +export function fromURI(uri: string): IRI; + +/** + * Returns an IRI string decoded from the given URI. + */ +export function toIRIString(uri: string): string; diff --git a/types/iri/iri-tests.ts b/types/iri/iri-tests.ts new file mode 100644 index 0000000000..97a460e02c --- /dev/null +++ b/types/iri/iri-tests.ts @@ -0,0 +1,43 @@ +import { IRI, fromURI, toIRIString } from 'iri'; + +const iri = new IRI('iri'); +// $ExpectType string +iri.toString(); +// $ExpectType IRI +iri.defrag(); +// $ExpectType boolean +iri.isAbsolute(); +// $ExpectType IRI +iri.toAbsolute(); +// $ExpectType string | null +iri.authority(); +// $ExpectType string | null +iri.fragment(); +// $ExpectType string +iri.hierpart(); +// $ExpectType string +iri.host(); +// $ExpectType string +iri.path(); +// $ExpectType string | null +iri.port(); +// $ExpectType string | null +iri.query(); +// $ExpectType IRI +iri.resolveReference('ref'); +iri.resolveReference(iri); +// $ExpectType string | null +iri.scheme(); +// $ExpectType string | null +iri.userinfo(); +// $ExpectType string +iri.toURIString(); +// $ExpectType string +iri.toIRIString(); +// $ExpectType IRI +iri.toIRI(); + +// $ExpectType IRI +fromURI('u'); +// $ExpectType string +toIRIString('u'); diff --git a/types/iri/tsconfig.json b/types/iri/tsconfig.json new file mode 100644 index 0000000000..09b1e0069e --- /dev/null +++ b/types/iri/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", + "iri-tests.ts" + ] +} diff --git a/types/iri/tslint.json b/types/iri/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iri/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e80e44b0f032fc4a70d6e4d05354a6e53fb9089b Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 21 Nov 2018 01:06:14 +0100 Subject: [PATCH 028/155] Update types for @xmpp/jid --- types/xmpp__jid/index.d.ts | 84 ++++++++++++++++-------------- types/xmpp__jid/xmpp__jid-tests.ts | 55 ++++++++++--------- 2 files changed, 73 insertions(+), 66 deletions(-) diff --git a/types/xmpp__jid/index.d.ts b/types/xmpp__jid/index.d.ts index f3f5bcc485..51b19051f1 100644 --- a/types/xmpp__jid/index.d.ts +++ b/types/xmpp__jid/index.d.ts @@ -1,55 +1,63 @@ -// Type definitions for @xmpp/jid 0.0 +// Type definitions for @xmpp/jid 0.6 // Project: https://github.com/node-xmpp/node-xmpp/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -export function createJID(local: string, domain: string, resource: string): JID; -export function equal(a: JID, b: JID): boolean; -export function is(a: any): boolean; +export = jid; -/** - * Created by marcneumann on 17.02.17. - */ -export class JID { - local: string; - domain: string; - resource: string; +declare function jid(address: string): jid.JID; +declare function jid(local: string | undefined, domain: string, resource?: string): jid.JID; - constructor(local: string, domain?: string, resource?: string); +declare namespace jid { + function jid(address: string): JID; + function jid(local: string | undefined, domain: string, resource?: string): JID; - parseJID(jid: string): void; + function createJID(local: string | undefined, domain: string, resource?: string): JID; + function equal(a: JID, b: JID): boolean; + function detectEscape(local?: string): boolean; + function escapeLocal(local: string): string; + function unescapeLocal(local: string): string; + function parse(s: string): JID; - toString(unescape?: any): string; + class JID { + local: string; + domain: string; + resource: string; - /** - * Convenience method to distinguish users - */ - bare(): JID; + constructor(local: string | undefined, domain: string, resource?: string); - /** - * Comparison function - */ - equals(other: JID): boolean; + toString(unescape?: boolean): string; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart - */ - setLocal(local: string, escape?: any): void; + /** + * Convenience method to distinguish users + */ + bare(): JID; - getLocal(unescape?: any): string; + /** + * Comparison function + */ + equals(other: JID): boolean; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-domain - */ - setDomain(value: string): void; + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart + */ + setLocal(local: string, escape?: boolean): void; - getDomain(): string; + getLocal(unescape?: boolean): string; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart - */ - setResource(value: string): void; + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-domain + */ + setDomain(value: string): void; - getResource(): string; + getDomain(): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart + */ + setResource(value: string): void; + + getResource(): string; + } } diff --git a/types/xmpp__jid/xmpp__jid-tests.ts b/types/xmpp__jid/xmpp__jid-tests.ts index d26ede9a15..4a79d5849f 100644 --- a/types/xmpp__jid/xmpp__jid-tests.ts +++ b/types/xmpp__jid/xmpp__jid-tests.ts @@ -1,40 +1,39 @@ -import { JID } from '@xmpp/jid'; +import jid = require('@xmpp/jid'); -/* - * All return an instance of JID.JID, the new operator is optional. - */ -let addr = new JID('alice@wonderland.net/rabbithole'); // OK -addr = new JID('alice', 'wonderland.net', 'rabbithole'); // BEST; see section on escaping below +let addr: jid.JID; +let str: string; +let bool: boolean; + +addr = jid('alice@wonderland.net/rabbithole'); +addr = jid('alice', 'wonderland.net', 'rabbithole'); -/* - * local - */ addr.local = 'alice'; -addr.local; // alice -// same as +str = addr.local; addr.setLocal('alice'); -addr.getLocal(); // alice +addr.setLocal('alice', true); +str = addr.getLocal(); -/* - * domain - */ addr.domain = 'wonderland.net'; -addr.domain; // wonderland.net -// same as +str = addr.domain; addr.setDomain('wonderland.net'); -addr.getDomain(); // wonderland.net +str = addr.getDomain(); -/* - * resource - */ addr.resource = 'rabbithole'; -addr.resource; // rabbithole -// same as +str = addr.resource; addr.setResource('rabbithole'); -addr.getResource(); // rabbithole +str = addr.getResource(); -addr.toString(); // alice@wonderland.net/rabbithole -addr.bare(); // returns a JID without resource +str = addr.toString(); +str = addr.toString(true); +addr = addr.bare(); -const some_jid = new JID('is', 'a', 'test'); -addr.equals(some_jid); // returns true if the two JIDs are equal, false otherwise +bool = addr.equals(addr); + +bool = jid.equal(addr, addr); + +addr = jid.createJID('my', 'homies'); +bool = jid.equal(addr, addr); +bool = jid.detectEscape('homies'); +str = jid.escapeLocal('homies'); +str = jid.unescapeLocal('homies'); +addr = jid.parse('homies'); From 43a1c3ef84dbfbe230c5386bb7a5d395d0562774 Mon Sep 17 00:00:00 2001 From: erikma Date: Sun, 25 Nov 2018 12:29:13 -0800 Subject: [PATCH 029/155] Update pigpio types to include changes up to version 1.2.0 --- types/pigpio/index.d.ts | 28 ++++++++++++++++++++++++++-- types/pigpio/pigpio-tests.ts | 9 +++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 79d0ebe0f9..1bc901f084 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pigpio 0.4 +// Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan +// Definitions by: ManerFan and erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -424,3 +424,27 @@ export function configureClock(microseconds: number, peripheral: number): void; * @param port an unsigned integer specifying the pigpio socket port number */ export function configureSocketPort(port: number): void; + +/** + * Returns the Raspberry Pi hardware revision as an unsigned integer. Returns 0 + * if the hardware revision can not be determined. + */ +export function hardwareRevision(): number; + +/** + * Gets the current unsigned 32-bit integer value of the number of microseconds + * since system boot. This value wraps around the 32-bit space in just over an hour. + * Use tickDiff() to get the difference between two tick values, to + * ensure the correct JavaScript operations are used to account for the possibility + * of overflow. + */ +export function getTick(): number; + +/** + * Returns the difference in microseconds between the end and start tick counts. + * The tick counts can be retrieved using getTick(), or may be passed + * in a GPIO event callback. + * @param startTick The start of the measured interval. An unsigned integer tick value. + * @param endTick The end of the measured interval. An unsigned integer tick value. + */ +export function tickDiff(startTick: number, endTick: number): number; diff --git a/types/pigpio/pigpio-tests.ts b/types/pigpio/pigpio-tests.ts index 90e7d4485d..f756058b03 100644 --- a/types/pigpio/pigpio-tests.ts +++ b/types/pigpio/pigpio-tests.ts @@ -880,6 +880,15 @@ import * as assert from 'assert'; }, 2000); })(); +(function tickAndTickDiff(): void { + const startTick: number = pigpio.getTick(); + setTimeout(() => { + const endTick: number = pigpio.getTick(); + const diff: number = pigpio.tickDiff(startTick, endTick); + assert.ok(diff > 0, 'expected tick count to increase across a timer call'); + }, 50); +})(); + (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { From 3465be17ba8e9ec2628e3bfae2d5b67cdd1955ac Mon Sep 17 00:00:00 2001 From: erikma Date: Sun, 25 Nov 2018 12:35:43 -0800 Subject: [PATCH 030/155] fix lint issue --- types/pigpio/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 1bc901f084..8eaa6491bb 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan and erikma +// Definitions by: ManerFan , erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 7416fd03c44b5a4d9e9ce6eb5bd4418d754adac0 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:42:31 +0100 Subject: [PATCH 031/155] Add encrypt and decrypt to Pubnub types --- types/pubnub/index.d.ts | 22 +++++++++++++++++++++- types/pubnub/pubnub-tests.ts | 12 ++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 8337acfbe4..1fc38edabf 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson +// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration @@ -88,6 +88,18 @@ declare class Pubnub { setState( params: Pubnub.SetStateParameters ): Promise; + + encrypt( + data: string, + customCipherKey?: string, + options?: Pubnub.CryptoParameters, + ): object | string | null; + + decrypt( + data: object, + customCipherKey?: string, + options?: Pubnub.CryptoParameters + ): object | string | null; } declare namespace Pubnub { @@ -296,6 +308,14 @@ declare namespace Pubnub { }; } + // encrypt + interface CryptoParameters { + encryptKey?: boolean; + keyEncoding?: string; + keyLength?: number; + mode?: string; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 1d8b2bb1ca..50660bd942 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -86,3 +86,15 @@ pubnub.setState({ channels: [] }, (status, res) => { pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); + +const cryptoOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc' +}; +const mySecret = { + message: 'Hi!', +}; +pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); From 147d828b80b191986af9e796d635e0cef3fdae14 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:44:14 +0100 Subject: [PATCH 032/155] Add comment for decrypt parameters --- types/pubnub/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 1fc38edabf..0b5f75901c 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -308,7 +308,7 @@ declare namespace Pubnub { }; } - // encrypt + // encrypt & decrypt interface CryptoParameters { encryptKey?: boolean; keyEncoding?: string; From 44ef75a9066b67df3e76d93f12bff05a408e7137 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:58:23 +0100 Subject: [PATCH 033/155] Add version note under header --- types/pubnub/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 0b5f75901c..7e148bc4c4 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration +// TypeScript Version: 2.2 declare class Pubnub { constructor(config: Pubnub.PubnubConfig); From 620ad409303126f5066dc1dda42ec23ce0bf2f4f Mon Sep 17 00:00:00 2001 From: Karol Samborski Date: Sun, 25 Nov 2018 22:50:42 +0100 Subject: [PATCH 034/155] Type definitions for multiSamlStrategy --- types/passport-saml/index.d.ts | 1 + types/passport-saml/passport-saml-tests.ts | 25 ++++++++++++++++++++++ types/passport-saml/tsconfig.json | 3 ++- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index cc2faafe5c..9338b88deb 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth // Damian Assennato +// Karol Samborski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 615c1b7320..b22421fe81 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -1,6 +1,7 @@ import express = require('express'); import passport = require('passport'); import SamlStrategy = require('passport-saml'); +import MultiSamlStrategy = require('passport-saml/multiSamlStrategy'); import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( @@ -33,3 +34,27 @@ passport.use(samlStrategy); passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); + +const multiSamlStrategy = new MultiSamlStrategy.MultiSamlStrategy( + { + name: 'samlCustomName', + path: '/login/callback', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlStrategy.SamlConfig) => void) { + callback(null, { + name: 'samlCustomName', + path: '/login/callback2', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + }); + } + }, + (profile: {}, done: (err: Error | null, user: {}, info?: {}) => void) => { + const user = {}; + done(null, user); + } +); + +passport.use(multiSamlStrategy); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); diff --git a/types/passport-saml/tsconfig.json b/types/passport-saml/tsconfig.json index 0809dbbaf7..39283fa663 100644 --- a/types/passport-saml/tsconfig.json +++ b/types/passport-saml/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "multiSamlStrategy.d.ts", "passport-saml-tests.ts" ] -} \ No newline at end of file +} From 58db065b6e539e777e8f0b9726fd187297651621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Alvergnat?= Date: Thu, 22 Nov 2018 22:54:38 +0100 Subject: [PATCH 035/155] Add types for deprecate --- types/deprecate/deprecate-tests.ts | 9 ++++++++ types/deprecate/index.d.ts | 33 ++++++++++++++++++++++++++++++ types/deprecate/tsconfig.json | 23 +++++++++++++++++++++ types/deprecate/tslint.json | 3 +++ 4 files changed, 68 insertions(+) create mode 100644 types/deprecate/deprecate-tests.ts create mode 100644 types/deprecate/index.d.ts create mode 100644 types/deprecate/tsconfig.json create mode 100644 types/deprecate/tslint.json diff --git a/types/deprecate/deprecate-tests.ts b/types/deprecate/deprecate-tests.ts new file mode 100644 index 0000000000..3df2257c40 --- /dev/null +++ b/types/deprecate/deprecate-tests.ts @@ -0,0 +1,9 @@ +import deprecate = require('deprecate'); + +deprecate('someMethod'); +deprecate('someMethod', 'This is deprecated'); +deprecate('someMethod', 'This is deprecated', 'foo', 'bar'); + +deprecate.color = '\x1b[31;1m'; +deprecate.silence = true; +deprecate.stream = process.stderr; diff --git a/types/deprecate/index.d.ts b/types/deprecate/index.d.ts new file mode 100644 index 0000000000..a053721ff5 --- /dev/null +++ b/types/deprecate/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for deprecate 1.1 +// Project: https://github.com/brianc/node-deprecate +// Definitions by: Toilal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare namespace deprecate { + /** + * Set to false to not output a color. Defaults to '\x1b[31;1m' which is red. + */ + let color: string; + + /** + * Set to false to do nothing at all when the deprecate method is called. Useful in tests of the library you're deprecating things within. + */ + let silence: boolean; + + /** + * The stream to which output is written. Defaults to process.stderr + */ + let stream: NodeJS.WriteStream; +} + +/** + * Call deprecate within a function you are deprecating. + * + * It will spit out all the messages to the console the first time and only the first time the method is called. + */ +declare function deprecate(methodName: string, ...message: string[]): void; + +export = deprecate; diff --git a/types/deprecate/tsconfig.json b/types/deprecate/tsconfig.json new file mode 100644 index 0000000000..75acd6cda6 --- /dev/null +++ b/types/deprecate/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", + "deprecate-tests.ts" + ] +} diff --git a/types/deprecate/tslint.json b/types/deprecate/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/deprecate/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From cc95a58bf19a53762240bcdabf1ac18c040a5904 Mon Sep 17 00:00:00 2001 From: Karol Samborski Date: Mon, 26 Nov 2018 07:13:25 +0100 Subject: [PATCH 036/155] Missing file --- types/passport-saml/multiSamlStrategy.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 types/passport-saml/multiSamlStrategy.d.ts diff --git a/types/passport-saml/multiSamlStrategy.d.ts b/types/passport-saml/multiSamlStrategy.d.ts new file mode 100644 index 0000000000..405c7264dc --- /dev/null +++ b/types/passport-saml/multiSamlStrategy.d.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import { Strategy, SamlConfig, VerifyWithRequest, VerifyWithoutRequest } from './index'; + +export interface MultiSamlConfig extends SamlConfig { + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlConfig) => void): void; +} + +export class MultiSamlStrategy extends Strategy { + constructor(config: MultiSamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); +} From 59bfd27bf6b5d17c6d9485d8d08b0db3e42add13 Mon Sep 17 00:00:00 2001 From: Jessica Date: Mon, 26 Nov 2018 19:09:42 +0900 Subject: [PATCH 037/155] Add support to the `css` prop from babel-plugin-styled-components --- types/styled-components/index.d.ts | 20 +++++++ types/styled-components/test/index.tsx | 74 +++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index a842c94c63..ee64b37772 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -436,4 +436,24 @@ export class StyleSheetManager extends React.Component< StyleSheetManagerProps > {} +export type CSSIntrinsicAttributeType = + | string + | CSSObject + | FlattenSimpleInterpolation + // Sad, but because this is global, there is no way to override it with the ThemedStyledComponentsModule + // Only augmenting DefaultTheme will work for inline css prop + | FlattenInterpolation>>; + export default styled; + +declare module "react" { + interface Attributes { + // NOTE: unlike the plain javascript version, it is not possible to get access + // to the element's own attributes inside function interpolations. + // Only theme will be accessible, and only with the DefaultTheme due to the global + // nature of this declaration. + // If you are writing this inline you already have access to all the attributes anyway, + // no need for the extra indirection. + css?: import(".").CSSIntrinsicAttributeType; // tslint:disable-line whitespace + } +} diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index e435d90011..c152ffd66e 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -172,7 +172,6 @@ const styledButton = styled.button` const name = "hey"; const ThemedMyButton = withTheme(MyButton); - ; /** @@ -290,7 +289,6 @@ const ObjectStylesBox = styled.div` fontSize: 2 }}; `; - ; /** @@ -322,7 +320,6 @@ const AttrsWithOnlyNewProps = styled.h2.attrs({ as: "h1" })` `; const AttrsInputExtra = styled(AttrsInput).attrs({ autoComplete: "off" })``; - ; /** @@ -419,10 +416,8 @@ const Component = (props: WithThemeProps) => ( ); const ComponentWithTheme = withTheme(Component); - ; // ok ; // ok - {theme => }; /** @@ -610,7 +605,6 @@ const divFnRef = (ref: HTMLDivElement | null) => { const divRef = React.createRef(); const StyledDiv = styled.div``; - ; ; ; // $ExpectError @@ -771,3 +765,71 @@ async function themeAugmentation() { ); } + +// NOTE: this is needed for some tests inside cssProp, +// but actually running this module augmentation will cause +// tests elsewhere to break, and there is no way to contain it. +// Uncomment out as needed to run tests. + +// declare module "styled-components" { +// interface DefaultTheme { +// background: string; +// } +// } + +function cssProp() { + function Custom(props: React.ComponentPropsWithoutRef<"div">) { + return
; + } + + return ( + <> +
+
+
+
+
"blue"}; + `} + /> +
{ + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + + + + "blue"}; + `} + /> + { + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + ); +} From 3fc77b020c5482986330cc606cddc0981052e784 Mon Sep 17 00:00:00 2001 From: Jessica Date: Mon, 26 Nov 2018 19:22:27 +0900 Subject: [PATCH 038/155] Fix the types in rebass__grid --- types/rebass__grid/index.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/rebass__grid/index.d.ts b/types/rebass__grid/index.d.ts index 079506e631..f49d43a6c6 100644 --- a/types/rebass__grid/index.d.ts +++ b/types/rebass__grid/index.d.ts @@ -10,7 +10,7 @@ export type Omit = Pick; import { ComponentType } from "react"; -import { StyledComponent, Interpolation } from "styled-components"; +import { StyledComponent, CSSIntrinsicAttributeType } from "styled-components"; export type ResponsiveProp = number | string | Array; @@ -34,7 +34,10 @@ export interface CommonProps { px?: ResponsiveProp; py?: ResponsiveProp; theme?: any; - css?: Interpolation; + /** + * NOTE: this is not compatible with the styled-components babel plugin anymore + */ + css?: CSSIntrinsicAttributeType; } export interface BoxProps From d3c9c35fc625641c4c95d54eef25a8c0d84e71a7 Mon Sep 17 00:00:00 2001 From: Mihkel Sokk Date: Mon, 26 Nov 2018 14:26:50 +0200 Subject: [PATCH 039/155] [ejs] renderFile returns Promise without callback, fixes #28934 --- types/ejs/ejs-tests.ts | 3 +++ types/ejs/index.d.ts | 2 ++ 2 files changed, 5 insertions(+) diff --git a/types/ejs/ejs-tests.ts b/types/ejs/ejs-tests.ts index 8a0b2404d7..881a3fe103 100644 --- a/types/ejs/ejs-tests.ts +++ b/types/ejs/ejs-tests.ts @@ -29,6 +29,9 @@ result = ejs.render(template, data, options); result = ejs.renderFile(fileName, SimpleCallback); result = ejs.renderFile(fileName, data, SimpleCallback); result = ejs.renderFile(fileName, data, options, SimpleCallback); +asyncResult = ejs.renderFile(fileName); +asyncResult = ejs.renderFile(fileName, data); +asyncResult = ejs.renderFile(fileName, data, options); ejsFunction = ejs.compile(''); ejsFunction = ejs.compile(read(fileName, "utf8")); diff --git a/types/ejs/index.d.ts b/types/ejs/index.d.ts index 73eb716e23..fc578cffff 100644 --- a/types/ejs/index.d.ts +++ b/types/ejs/index.d.ts @@ -54,6 +54,8 @@ export type RenderFileCallback = (err: Error, str?: string) => T; export function renderFile(path: string, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; +// tslint:disable-next-line no-unnecessary-generics +export function renderFile(path: string, data?: Data, opts?: Options): Promise; /** * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. From a941c86b563f56f65e6038c6f35debe28fba2514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ba=C4=8D=C3=ADk?= Date: Mon, 26 Nov 2018 14:57:35 +0100 Subject: [PATCH 040/155] Added RN Image width and height props --- types/react-native/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2386fc71c2..112abe79a9 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,6 +3629,12 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; + + /** + * Required sizes if using native image resources on Android + */ + width?: number; + height?: number; } /** From 18d0d101f1c388ce03b6f815337e195fd92fd1d8 Mon Sep 17 00:00:00 2001 From: Kai Dorschner Date: Mon, 26 Nov 2018 15:05:20 +0100 Subject: [PATCH 041/155] Add missing inputIconPosition to type definition. see http://airbnb.io/react-dates/?selectedKind=DRP%20-%20Input%20Props&selectedStory=with%20show%20calendar%20icon%20after%20input&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Factions%2Factions-panel --- types/react-dates/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 05058b2ca9..9e96538f7d 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -55,6 +55,7 @@ declare namespace ReactDates { screenReaderInputMessage?: string, showClearDates?: boolean, showDefaultInputIcon?: boolean, + inputIconPosition?: IconPositionShape, customInputIcon?: string | JSX.Element, customArrowIcon?: string | JSX.Element, customCloseIcon?: string | JSX.Element, From ce71e7bb557834aa38e36ed35903d80cb35bb4cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ba=C4=8D=C3=ADk?= Date: Mon, 26 Nov 2018 15:40:11 +0100 Subject: [PATCH 042/155] Removed whitespace --- types/react-native/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 112abe79a9..15423558e4 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,7 +3629,7 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; - + /** * Required sizes if using native image resources on Android */ From f675d110aae80c33bdc289624c85052a2a1dc858 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Mon, 26 Nov 2018 16:16:36 +0100 Subject: [PATCH 043/155] Change crypto payload to any --- types/pubnub/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 7e148bc4c4..257ca3cd44 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -94,13 +94,13 @@ declare class Pubnub { data: string, customCipherKey?: string, options?: Pubnub.CryptoParameters, - ): object | string | null; + ): any; decrypt( data: object, customCipherKey?: string, options?: Pubnub.CryptoParameters - ): object | string | null; + ): any; } declare namespace Pubnub { From 35483b43559b94114dca755f130e6ccb48f18d3b Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 20:30:14 +0100 Subject: [PATCH 044/155] Impove types for bitwise-xor --- types/bitwise-xor/bitwise-xor-tests.ts | 12 ++-- types/bitwise-xor/index.d.ts | 7 +-- types/bitwise-xor/tsconfig.json | 4 +- types/bitwise-xor/tslint.json | 78 +------------------------- 4 files changed, 11 insertions(+), 90 deletions(-) diff --git a/types/bitwise-xor/bitwise-xor-tests.ts b/types/bitwise-xor/bitwise-xor-tests.ts index b19768f11f..13ddab8b66 100644 --- a/types/bitwise-xor/bitwise-xor-tests.ts +++ b/types/bitwise-xor/bitwise-xor-tests.ts @@ -1,10 +1,8 @@ +'use strict'; +import xor = require('bitwise-xor'); -"use strict"; +let b: Buffer; -import xor = require("bitwise-xor"); - -var b: Buffer; - -b = xor("a", "b"); -b = xor(new Buffer("a"), new Buffer("b")); +b = xor('a', 'b'); +b = xor(new Buffer('a'), new Buffer('b')); diff --git a/types/bitwise-xor/index.d.ts b/types/bitwise-xor/index.d.ts index 9960023c97..3147c5b675 100644 --- a/types/bitwise-xor/index.d.ts +++ b/types/bitwise-xor/index.d.ts @@ -1,15 +1,14 @@ -// Type definitions for bitwise-xor 0.0.0 +// Type definitions for bitwise-xor 0.0 // Project: https://github.com/czzarr/node-bitwise-xor // Definitions by: Rogier Schouten +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - /** * Bitwise XOR between two Buffers or Strings, returns a Buffer */ -declare function xor(b1: Buffer, b2: Buffer): Buffer; -declare function xor(s1: string, s2: string): Buffer; +declare function xor(a: Buffer | string, b: Buffer | string): Buffer; export = xor; diff --git a/types/bitwise-xor/tsconfig.json b/types/bitwise-xor/tsconfig.json index a6b66cda37..f02f5ef72b 100644 --- a/types/bitwise-xor/tsconfig.json +++ b/types/bitwise-xor/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "bitwise-xor-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bitwise-xor/tslint.json b/types/bitwise-xor/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/bitwise-xor/tslint.json +++ b/types/bitwise-xor/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From b41337dd487ca3a99359e93a9067073643870d99 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:15:37 +0100 Subject: [PATCH 045/155] Add types for create-hmac --- types/create-hmac/create-hmac-tests.ts | 9 +++++++++ types/create-hmac/index.d.ts | 26 ++++++++++++++++++++++++++ types/create-hmac/tsconfig.json | 23 +++++++++++++++++++++++ types/create-hmac/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/create-hmac/create-hmac-tests.ts create mode 100644 types/create-hmac/index.d.ts create mode 100644 types/create-hmac/tsconfig.json create mode 100644 types/create-hmac/tslint.json diff --git a/types/create-hmac/create-hmac-tests.ts b/types/create-hmac/create-hmac-tests.ts new file mode 100644 index 0000000000..f233a0390a --- /dev/null +++ b/types/create-hmac/create-hmac-tests.ts @@ -0,0 +1,9 @@ +import createHmac = require('create-hmac'); + +const hmac = createHmac('sha224', Buffer.from('secret key')); + +hmac.update('synchronous write'); +hmac.digest(); +hmac.write('write to it as a stream'); +hmac.end(); +hmac.read(); diff --git a/types/create-hmac/index.d.ts b/types/create-hmac/index.d.ts new file mode 100644 index 0000000000..3d6bcfeafa --- /dev/null +++ b/types/create-hmac/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hmac 1.1 +// Project: https://github.com/crypto-browserify/createHmac +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hmac } from 'crypto'; + +export = createHmac; + +declare function createHmac(algo: createHmac.Algorithm, key: string | Buffer): Hmac; + +declare namespace createHmac { + type Algorithm = + | 'rmd160' + | 'ripemd160' + | 'md5' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hmac/tsconfig.json b/types/create-hmac/tsconfig.json new file mode 100644 index 0000000000..badd99da29 --- /dev/null +++ b/types/create-hmac/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", + "create-hmac-tests.ts" + ] +} diff --git a/types/create-hmac/tslint.json b/types/create-hmac/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hmac/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7e23c69081ef5211b821463eb9c223e891c7a456 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:31:11 +0200 Subject: [PATCH 046/155] Update definitions to accommodate API changes InputProps are now optional. The Component now receives props via direct application. --- types/react-places-autocomplete/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..26046fc06f 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -15,9 +15,7 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; @@ -49,6 +47,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; From f5e979aa4e03525afab03c4bff3c339762b57314 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:53:21 +0200 Subject: [PATCH 047/155] fix optional inputs --- types/react-places-autocomplete/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 26046fc06f..f95164a89d 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -19,7 +19,6 @@ export interface PropTypes { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -47,7 +46,7 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; - value: string; + value?: string; onChange?: (value: string) => void; onBlur?: (event: React.FocusEvent) => void; From f4f4074e189ffb8b461566c4430bd3d4620daa17 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:55:07 +0200 Subject: [PATCH 048/155] Update types 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 f95164a89d..19d53c863d 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 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov From 0a3010fe25eaded32b64e515df877479ca13cb53 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:57:11 +0200 Subject: [PATCH 049/155] Update Tests --- .../react-places-autocomplete-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..a7a7816d99 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -45,7 +45,7 @@ class Test extends React.Component { return (
- + ); } From 4731065fe25d5aa1e192166802321482db70dd21 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 17:02:42 +0200 Subject: [PATCH 050/155] Update index.d.ts --- 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 19d53c863d..6a6a85c19e 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 7 +// 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 cf4ed80a0837167bd53fdb9d23321fac19468efc Mon Sep 17 00:00:00 2001 From: NN Date: Tue, 27 Nov 2018 17:58:48 +0200 Subject: [PATCH 051/155] Fix #30848 configHash can be a string in HardSourceWebpackPlugin --- types/hard-source-webpack-plugin/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/hard-source-webpack-plugin/index.d.ts b/types/hard-source-webpack-plugin/index.d.ts index 3e02ee1d8a..4a83b58034 100644 --- a/types/hard-source-webpack-plugin/index.d.ts +++ b/types/hard-source-webpack-plugin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hard-source-webpack-plugin 0.9 +// Type definitions for hard-source-webpack-plugin 1.0 // Project: https://github.com/mzgoddard/hard-source-webpack-plugin#readme // Definitions by: woitechen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace hard_source_webpack_plugin { } interface Options { cacheDirectory?: string; - configHash?: (webpackConfig?: webpack.Configuration) => string; + configHash?: string | ((webpackConfig?: webpack.Configuration) => string); environmentHash?: { root: string; directories: string[]; From 289c533aadb4ee5d6a7ef2a740c4d38cd7b6cc59 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 17:27:21 +0000 Subject: [PATCH 052/155] [@babel/traverse]: Fixed type of path when using enter & exit visitor. --- types/babel__traverse/babel__traverse-tests.ts | 8 ++++++-- types/babel__traverse/index.d.ts | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 5b4fbbef5f..974831dbca 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -4,10 +4,14 @@ import * as t from "@babel/types"; // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { - enter() { + enter(path) { + // $ExpectType NodePath + path; console.log("Entered!"); }, - exit() { + exit(path) { + // $ExpectType NodePath + path; console.log("Exited!"); } } diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 465a60464f..740f5f4429 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -142,7 +142,7 @@ export type Visitor = VisitNodeObject & { [P in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject

; export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; From f757203084ed5793a80255c032740738d0a82c86 Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Tue, 27 Nov 2018 11:44:14 -0700 Subject: [PATCH 053/155] [react-datepicker] v2.0.0 --- types/react-datepicker/index.d.ts | 69 ++++++++++++++++++----------- types/react-datepicker/package.json | 1 - 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 23e542d322..6368e273e3 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.1 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -7,11 +7,11 @@ // Roy Xue // Koala Human // Sean Kelley +// Jake Boone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -import * as moment from "moment"; import * as Popper from "popper.js"; export interface ReactDatePickerProps { @@ -20,59 +20,65 @@ export interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; dateFormatCalendar?: string; - dayClassName?(date: moment.Moment): string | null; + dayClassName?(date: Date): string | null; disabled?: boolean; disabledKeyboardNavigation?: boolean; dropdownMode?: 'scroll' | 'select'; - endDate?: moment.Moment; - excludeDates?: moment.Moment[]; - excludeTimes?: moment.Moment[]; - filterDate?(date: moment.Moment): boolean; + endDate?: Date; + excludeDates?: Date[]; + excludeTimes?: Date[]; + filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; - formatWeekNumber?(date: moment.Moment): string | number; - highlightDates?: moment.Moment[]; + formatWeekNumber?(date: Date): string | number; + highlightDates?: Date[]; id?: string; - includeDates?: moment.Moment[]; - includeTimes?: moment.Moment[]; + includeDates?: Date[]; + includeTimes?: Date[]; + injectTimes?: Date[]; inline?: boolean; isClearable?: boolean; locale?: string; - maxDate?: moment.Moment; - maxTime?: moment.Moment; - minDate?: moment.Moment; - minTime?: moment.Moment; + maxDate?: Date; + maxTime?: Date; + minDate?: Date; + minTime?: Date; monthsShown?: number; name?: string; onBlur?(event: React.FocusEvent): void; - onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): void; + onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; onKeyDown?(event: React.KeyboardEvent): void; - onMonthChange?(date: moment.Moment): void; - onSelect?(date: moment.Moment, event: React.SyntheticEvent | undefined): void; - onWeekSelect?(firstDayOfWeek: moment.Moment, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onYearChange?(date: moment.Moment): void; - openToDate?: moment.Moment; + onMonthChange?(date: Date): void; + onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; + onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; + onInputClick?(): void; + onYearChange?(date: Date): void; + onInputError?(err: {code: number; msg: string}): void; + open?: boolean; + openToDate?: Date; peekNextMonth?: boolean; placeholderText?: string; popperClassName?: string; popperContainer?(props: { children: React.ReactNode[] }): React.ReactNode; popperModifiers?: Popper.Modifiers; popperPlacement?: string; + popperProps?: {}; preventOpenOnFocus?: boolean; readOnly?: boolean; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -83,21 +89,34 @@ export interface ReactDatePickerProps { showTimeSelectOnly?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; - startDate?: moment.Moment; + startDate?: Date; startOpen?: boolean; tabIndex?: number; timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; - todayButton?: string; + todayButton?: React.ReactNode; useShortMonthInDropdown?: boolean; useWeekdaysShort?: boolean; - utcOffset?: number; value?: string; weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; + formatWeekDay?(date: Date): string; + clearButtonTitle?: string; + previousMonthButtonLabel?: string; + nextMonthButtonLabel?: string; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; diff --git a/types/react-datepicker/package.json b/types/react-datepicker/package.json index fc763e4d4b..245f69cd2c 100644 --- a/types/react-datepicker/package.json +++ b/types/react-datepicker/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "moment": ">=2.14.0", "popper.js": "^1.14.1" } } From c3f0ee0d5d9765ac9fe65da8c75e477a71e398ca Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Tue, 27 Nov 2018 11:55:08 -0700 Subject: [PATCH 054/155] [react-datepicker] fix v2 tests --- types/react-datepicker/react-datepicker-tests.tsx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1414672684..4a3fd93cac 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,16 @@ import * as React from 'react'; -import * as moment from 'moment'; import DatePicker from 'react-datepicker'; {}} - onYearChange={(date: moment.Moment) => {}} + selected={new Date()} + onChange={(date: Date | null) => {}} + onYearChange={(date: Date) => {}} popperModifiers={{ flip: { enabled: false } }} - includeTimes={[moment()]} + includeTimes={[new Date()]} >

From 0226045de5e8db79594af54dbab3f5b77b972d3c Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 20:42:30 +0000 Subject: [PATCH 055/155] Implemented all changes outlined in the comments in pull request #30862. --- .../babel__traverse/babel__traverse-tests.ts | 37 +++++++++++++++++++ types/babel__traverse/index.d.ts | 14 +++---- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 974831dbca..772b392b63 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -112,3 +112,40 @@ const BindingKindTest: Visitor = { // kind === 'anythingElse'; }, }; + +interface SomeVisitorState { someState: string; } + +const VisitorStateTest: Visitor = { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + Identifier(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + FunctionDeclaration: { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + } + } +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 740f5f4429..a0a3730057 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -138,17 +138,17 @@ export class Binding { constantViolations: NodePath[]; } -export type Visitor = VisitNodeObject & { - [P in Node["type"]]?: VisitNode>; +export type Visitor = VisitNodeObject & { + [Type in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject

; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; +export type VisitNodeFunction = (this: S, path: NodePath

, state: S) => void; -export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; +export interface VisitNodeObject { + enter?: VisitNodeFunction; + exit?: VisitNodeFunction; } export class NodePath { From 00f1245e599f463b2ea16b4e77e85bf73f9cbca5 Mon Sep 17 00:00:00 2001 From: piotr rotynski Date: Tue, 27 Nov 2018 23:22:07 +0100 Subject: [PATCH 056/155] Adding withArgs method to Spy interface as per Jasmine's docs for v3.3 --- types/jasmine/index.d.ts | 1 + types/jasmine/jasmine-tests.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index e9dba1e2cd..a87b8b3a86 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -639,6 +639,7 @@ declare namespace jasmine { calls: Calls; mostRecentCall: { args: any[]; }; argsForCall: any[]; + withArgs(...args: any[]): Spy; } type SpyObj = T & { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index ba8763ce3d..92f9a21db8 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -469,6 +469,40 @@ describe("A spy, when configured with an alternate implementation", () => { }); }); +describe("A spy, when configured with alternate implementations for specified arguments", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar") + .withArgs(1, "2") + .and.callFake(() => 1002); + + foo.setBar(123); + fetchedBar = foo.getBar(1, "2"); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1002); + }); +}); + describe("A spy, when configured to throw a value", () => { var foo: any, bar: any; From c63de7c41921667f3bc0723d6206c78bae4ae230 Mon Sep 17 00:00:00 2001 From: timhwang21 Date: Tue, 27 Nov 2018 18:03:50 -0500 Subject: [PATCH 057/155] [bip39] Add Buffer as valid argument for entropyToMnemonic The function accepts either string or buffer. --- types/bip39/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bip39/index.d.ts b/types/bip39/index.d.ts index a5d58cf961..6894ac3b30 100644 --- a/types/bip39/index.d.ts +++ b/types/bip39/index.d.ts @@ -17,7 +17,7 @@ export const wordlists: { spanish: string[]; }; -export function entropyToMnemonic(entropyHex: string, wordlist?: string[]): string; +export function entropyToMnemonic(entropyHex: Buffer | string, wordlist?: string[]): string; export function generateMnemonic(strength?: number, rng?: (size: number) => Buffer, wordlist?: string[]): string; From 53771da91e57c816f8f1899c2e4e072a9bcf97f8 Mon Sep 17 00:00:00 2001 From: Chris Arnesen Date: Wed, 28 Nov 2018 14:15:24 +0700 Subject: [PATCH 058/155] Add options arg to "find-versions" --- types/find-versions/find-versions-tests.ts | 3 ++- types/find-versions/index.d.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/find-versions/find-versions-tests.ts b/types/find-versions/find-versions-tests.ts index 81ea6ca974..e92e6d9848 100644 --- a/types/find-versions/find-versions-tests.ts +++ b/types/find-versions/find-versions-tests.ts @@ -1,3 +1,4 @@ import findVersions = require('find-versions'); -findVersions('node v1.0.0'); +findVersions('node v1.0.0'); // $ExpectType string[] +findVersions('1.0', { loose: true }); // $ExpectType string[] diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 449c5a45c3..f22e3796e2 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -3,5 +3,5 @@ // Definitions by: Leonid Logvinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function findVersions(version: string): string[]; +declare function findVersions(version: string, options?: { loose: boolean }): string[]; export = findVersions; From 95b52bea5276fb948958f3d8e4929954b27fd39c Mon Sep 17 00:00:00 2001 From: Chris Arnesen Date: Wed, 28 Nov 2018 14:22:42 +0700 Subject: [PATCH 059/155] Update metadata --- types/find-versions/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index f22e3796e2..7151227fb2 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for find-versions 2.0 +// Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov +// Chris Arnesen Date: Wed, 28 Nov 2018 15:29:38 +0700 Subject: [PATCH 060/155] Update types/find-versions/index.d.ts --- types/find-versions/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 7151227fb2..9531c1628f 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov -// Chris Arnesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function findVersions(version: string, options?: { loose: boolean }): string[]; From e8b63b0bdafe5b3f86c1f2eb062e77aef9fe99c6 Mon Sep 17 00:00:00 2001 From: Mathieu Ghennassia Date: Wed, 28 Nov 2018 11:52:15 +0100 Subject: [PATCH 061/155] mongodb: Type parameter update of method findOneAndUpdate --- types/mongodb/index.d.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index ab4d2f4c02..f994ade210 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -79,7 +79,7 @@ export interface ClientSession extends EventEmitter { /** The server id associated with this session */ id: any; /** - * Aborts the currently active transaction in this session. + * Aborts the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; @@ -89,7 +89,7 @@ export interface ClientSession extends EventEmitter { */ advanceOperationTime(operamtionTime: Timestamp): void; /** - * Commits the currently active transaction in this session. + * Commits the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; @@ -110,7 +110,7 @@ export interface ClientSession extends EventEmitter { * Used to determine if this session equals another * * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @returns {boolean} if the sessions are equal */ equals(session: ClientSession): boolean; @@ -118,13 +118,13 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns {boolean} this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options + * @param {TransactionOptions} options * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -219,10 +219,10 @@ export class MongoError extends Error { * client/user (eg. "Email address must be unique" instead of "Both email * address and username must be unique") - which caters for a better (app) * user experience. - * + * * Details: https://github.com/Automattic/mongoose/issues/2129 (issue for * mongoose, but the same applies for the native mongodb driver) - * + * * Note that in mongoose (the link above) the prop in question is called * 'message' while in mongodb it is called 'errmsg'. This can be seen in * multiple places in the source code, for example here: @@ -706,9 +706,9 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ - findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; From 1bec72c66668b0fd21dc7b23d7a9deae265ffa59 Mon Sep 17 00:00:00 2001 From: Adam Misiorny Date: Wed, 28 Nov 2018 12:56:06 +0100 Subject: [PATCH 062/155] [rosie] Fix sequence definition with builder argument --- types/rosie/index.d.ts | 2 +- types/rosie/rosie-tests.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/rosie/index.d.ts b/types/rosie/index.d.ts index 1078b53573..e66e9855eb 100644 --- a/types/rosie/index.d.ts +++ b/types/rosie/index.d.ts @@ -163,7 +163,7 @@ declare namespace rosie { * @param {function(number): *=} builder * @return {Factory} */ - sequence(name: keyof T, dependenciesOrBuilder?: () => any | keyof T[], builder?: Function) : IFactory; + sequence(name: keyof T, dependenciesOrBuilder?: (i: number) => any | keyof T[], builder?: Function) : IFactory; /** * Sets a post-processor callback that will receive built objects and the diff --git a/types/rosie/rosie-tests.ts b/types/rosie/rosie-tests.ts index 6c2152a9e7..86dd049732 100644 --- a/types/rosie/rosie-tests.ts +++ b/types/rosie/rosie-tests.ts @@ -19,6 +19,7 @@ resultObj = Factory.build('some'); Factory.define('coach') .option('buildPlayer', false) .sequence('id') + .sequence('name', (i: number) => `Coach${i}`) .attr('players', ['id', 'buildPlayer'], function(id: any, buildPlayer: boolean) { if (buildPlayer) { return [Factory.build('player', {coach_id: id})]; From d0081bef8b40ab5d104694063131acc928e5f78b Mon Sep 17 00:00:00 2001 From: HarikiRito <35214929+HarikiRito@users.noreply.github.com> Date: Wed, 28 Nov 2018 19:41:26 +0700 Subject: [PATCH 063/155] Export Interface --- types/react-lottie/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index 8e4f3b717b..a57da91307 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -7,7 +7,7 @@ import * as React from 'react'; -interface Options { +export interface Options { /** * Defines if the animation should play only once or repeatedly in an endless loop */ @@ -41,7 +41,7 @@ interface Options { }; } -interface EventListener { +export interface EventListener { /** * The event sent by Lottie */ @@ -61,7 +61,7 @@ interface EventListener { callback: () => void; } -interface LottieProps { +export interface LottieProps { /** * Object representing animation settings */ From 19d012663d76ff38c8ade084095cfef40556fad2 Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Wed, 28 Nov 2018 17:25:18 +0300 Subject: [PATCH 064/155] add on-initial-draw-complete-support --- types/vis/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 0f4a4f0f4e..9967c35061 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -11,6 +11,7 @@ // Oleksii Kachura // dcop // Avraham Essoudry +// Dmitriy Trifonov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { MomentInput, MomentFormatSpecification, Moment } from 'moment'; @@ -244,6 +245,7 @@ export interface TimelineOptions { multiselectPerGroup?: boolean; onAdd?: TimelineOptionsItemCallbackFunction; onAddGroup?: TimelineOptionsGroupCallbackFunction; + onInitialDrawComplete?: () => void; onUpdate?: TimelineOptionsItemCallbackFunction; onMove?: TimelineOptionsItemCallbackFunction; onMoveGroup?: TimelineOptionsGroupCallbackFunction; From b53181d81ab75724f19b0f1fb242525639c1f96f Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Wed, 28 Nov 2018 17:36:58 +0300 Subject: [PATCH 065/155] change void function type --- types/vis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 9967c35061..84ff769270 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -245,7 +245,7 @@ export interface TimelineOptions { multiselectPerGroup?: boolean; onAdd?: TimelineOptionsItemCallbackFunction; onAddGroup?: TimelineOptionsGroupCallbackFunction; - onInitialDrawComplete?: () => void; + onInitialDrawComplete?: (() => void); onUpdate?: TimelineOptionsItemCallbackFunction; onMove?: TimelineOptionsItemCallbackFunction; onMoveGroup?: TimelineOptionsGroupCallbackFunction; From 0f51eb8eeab7859c7eafbc3506f5ab65d3cfc267 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 16:23:49 +0100 Subject: [PATCH 066/155] Add types for mustache-express --- types/mustache-express/index.d.ts | 23 +++++++++++++++++++ .../mustache-express-tests.ts | 10 ++++++++ types/mustache-express/tsconfig.json | 23 +++++++++++++++++++ types/mustache-express/tslint.json | 1 + 4 files changed, 57 insertions(+) create mode 100644 types/mustache-express/index.d.ts create mode 100644 types/mustache-express/mustache-express-tests.ts create mode 100644 types/mustache-express/tsconfig.json create mode 100644 types/mustache-express/tslint.json diff --git a/types/mustache-express/index.d.ts b/types/mustache-express/index.d.ts new file mode 100644 index 0000000000..ff40de42d7 --- /dev/null +++ b/types/mustache-express/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for mustache-express 1.2 +// Project: https://github.com/bryanburgers/node-mustache-express#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Cache } from 'lru-cache'; + +export = mustacheExpress; + +declare function mustacheExpress( + partialsPath?: string, + partialsExt?: string +): mustacheExpress.ExpessEngine; + +declare namespace mustacheExpress { + interface ExpessEngine { + (path: string, options: any, cb: (...args: any[]) => any): any; + cache: TemplateCache; + } + + type TemplateCache = Cache; +} diff --git a/types/mustache-express/mustache-express-tests.ts b/types/mustache-express/mustache-express-tests.ts new file mode 100644 index 0000000000..9157798c7b --- /dev/null +++ b/types/mustache-express/mustache-express-tests.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import mustacheExpress = require('mustache-express'); + +const app = express(); +app.engine('mustache', mustacheExpress()); +app.engine('mustache', mustacheExpress('/partials')); +app.engine('mustache', mustacheExpress('/partials', '.mst')); + +// $ExpectType Cache +mustacheExpress().cache; diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json new file mode 100644 index 0000000000..9afb989b62 --- /dev/null +++ b/types/mustache-express/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", + "mustache-express-tests.ts" + ] +} diff --git a/types/mustache-express/tslint.json b/types/mustache-express/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mustache-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f857ba9d66d2f430fb2ff06b7e4579fbf61b7673 Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 28 Nov 2018 11:17:01 -0500 Subject: [PATCH 067/155] Added CollationDocument type in a couple places that were missed --- types/mongodb/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index a217b0a605..3de97daf60 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -526,7 +526,7 @@ export interface CollectionCreateOptions extends CommonOptions { indexOptionDefaults?: object; viewOn?: string; pipeline?: any[]; - collation?: object; + collation?: CollationDocument; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ @@ -563,7 +563,7 @@ export interface IndexOptions extends CommonOptions { name?: string; // Creates a partial index based on the given filter object (MongoDB 3.2 or higher) partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } From 5cc01bba1447d578d0c0c8b4fe80d599638b9dc0 Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 28 Nov 2018 11:37:45 -0500 Subject: [PATCH 068/155] Fixed incorrect type for caseFirst in CollationDocument --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 3de97daf60..ef7b7768d8 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1786,7 +1786,7 @@ export interface CollationDocument { locale: string; strength?: number; caseLevel?: boolean; - caseFirst?: boolean; + caseFirst?: string; numericOrdering?: boolean; alternate?: string; maxVariable?: string; From 64e8c6d752ddc75d26fcfed5478e2b5eb0a863f4 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 19:36:59 +0100 Subject: [PATCH 069/155] Add types for timing-safe-equal --- types/timing-safe-equal/index.d.ts | 10 ++++++++ .../timing-safe-equal-tests.ts | 5 ++++ types/timing-safe-equal/tsconfig.json | 23 +++++++++++++++++++ types/timing-safe-equal/tslint.json | 1 + 4 files changed, 39 insertions(+) create mode 100644 types/timing-safe-equal/index.d.ts create mode 100644 types/timing-safe-equal/timing-safe-equal-tests.ts create mode 100644 types/timing-safe-equal/tsconfig.json create mode 100644 types/timing-safe-equal/tslint.json diff --git a/types/timing-safe-equal/index.d.ts b/types/timing-safe-equal/index.d.ts new file mode 100644 index 0000000000..e1bf8f16d8 --- /dev/null +++ b/types/timing-safe-equal/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for timing-safe-equal 1.0 +// Project: https://github.com/crypto-browserify/timing-safe-equal +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = timingSafeEqual; + +declare function timingSafeEqual(a: Buffer, b: Buffer): boolean; diff --git a/types/timing-safe-equal/timing-safe-equal-tests.ts b/types/timing-safe-equal/timing-safe-equal-tests.ts new file mode 100644 index 0000000000..cc8069de3b --- /dev/null +++ b/types/timing-safe-equal/timing-safe-equal-tests.ts @@ -0,0 +1,5 @@ +import timingSafeEqual = require('timing-safe-equal'); + +const buffer: Buffer = new Buffer([1, 2, 3, 4, 5]); +// $ExpectType boolean +timingSafeEqual(buffer, buffer); diff --git a/types/timing-safe-equal/tsconfig.json b/types/timing-safe-equal/tsconfig.json new file mode 100644 index 0000000000..f12ec7b09e --- /dev/null +++ b/types/timing-safe-equal/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", + "timing-safe-equal-tests.ts" + ] +} diff --git a/types/timing-safe-equal/tslint.json b/types/timing-safe-equal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/timing-safe-equal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 01972623953bfefc9378b829bf1afd21a550d504 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 20:27:35 +0100 Subject: [PATCH 070/155] Add types for diffie-hellman --- types/diffie-hellman/diffie-hellman-tests.ts | 48 ++++++++++++++++++++ types/diffie-hellman/index.d.ts | 8 ++++ types/diffie-hellman/tsconfig.json | 23 ++++++++++ types/diffie-hellman/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 types/diffie-hellman/diffie-hellman-tests.ts create mode 100644 types/diffie-hellman/index.d.ts create mode 100644 types/diffie-hellman/tsconfig.json create mode 100644 types/diffie-hellman/tslint.json diff --git a/types/diffie-hellman/diffie-hellman-tests.ts b/types/diffie-hellman/diffie-hellman-tests.ts new file mode 100644 index 0000000000..645ebc23bd --- /dev/null +++ b/types/diffie-hellman/diffie-hellman-tests.ts @@ -0,0 +1,48 @@ +import * as dh from 'diffie-hellman'; + +const dh1 = dh.getDiffieHellman('modp1'); +// $ExpectType DiffieHellman +dh1; +// $ExpectType Buffer +dh1.generateKeys(); +// $ExpectType string +dh1.generateKeys('hex'); +// $ExpectType Buffer +dh1.getPrime(); +// $ExpectType string +dh1.getPrime('hex'); +// $ExpectType Buffer +dh1.getGenerator(); +// $ExpectType string +dh1.getGenerator('hex'); +const pk = dh1.getPublicKey(); +// $ExpectType Buffer +pk; +// $ExpectType string +dh1.getPublicKey('hex'); +// $ExpectType Buffer +dh1.getPrivateKey(); +// $ExpectType string +dh1.getPrivateKey('hex'); +// $ExpectType Buffer +dh1.computeSecret(pk); +// $ExpectType Buffer +dh1.computeSecret(pk.toString('hex'), 'hex'); +// $ExpectType string +dh1.computeSecret(pk.toString('hex'), 'hex', 'hex'); + +const dh2 = dh.createDiffieHellman(new Buffer([5])); +// $ExpectType DiffieHellman +dh2; +dh.createDiffieHellman('prime', 'hex'); +dh.createDiffieHellman('prime', 'hex', new Buffer([5])); +dh.createDiffieHellman('prime', 'hex', 5); +dh.createDiffieHellman('prime', 'hex', 'generator', 'hex'); +dh.createDiffieHellman(1); +dh.createDiffieHellman(1, 1); +dh.createDiffieHellman(1, new Buffer([5])); + +dh2.setPublicKey(pk); +dh2.setPublicKey(pk.toString('hex'), 'hex'); +dh2.setPrivateKey(pk); +dh2.setPrivateKey(pk.toString('hex'), 'hex'); diff --git a/types/diffie-hellman/index.d.ts b/types/diffie-hellman/index.d.ts new file mode 100644 index 0000000000..7b59cf9182 --- /dev/null +++ b/types/diffie-hellman/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for diffie-hellman 5.0 +// Project: https://github.com/crypto-browserify/diffie-hellman +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export { createDiffieHellman, getDiffieHellman, DiffieHellman } from 'crypto'; diff --git a/types/diffie-hellman/tsconfig.json b/types/diffie-hellman/tsconfig.json new file mode 100644 index 0000000000..743c9eea4c --- /dev/null +++ b/types/diffie-hellman/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", + "diffie-hellman-tests.ts" + ] +} diff --git a/types/diffie-hellman/tslint.json b/types/diffie-hellman/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/diffie-hellman/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 47a20469245d7c747192ac25ab769e8d23e2b5ac Mon Sep 17 00:00:00 2001 From: Elizabeth Craig Date: Wed, 28 Nov 2018 18:37:23 -0800 Subject: [PATCH 071/155] Add definitions for jju --- types/jju/index.d.ts | 213 ++++++++++++++++++++++++++++++++++++++++ types/jju/jju-tests.ts | 4 + types/jju/tsconfig.json | 23 +++++ types/jju/tslint.json | 1 + 4 files changed, 241 insertions(+) create mode 100644 types/jju/index.d.ts create mode 100644 types/jju/jju-tests.ts create mode 100644 types/jju/tsconfig.json create mode 100644 types/jju/tslint.json diff --git a/types/jju/index.d.ts b/types/jju/index.d.ts new file mode 100644 index 0000000000..46fbf2f77b --- /dev/null +++ b/types/jju/index.d.ts @@ -0,0 +1,213 @@ +// Type definitions for jju 1.4 +// Project: https://github.com/rlidwka/jju +// Definitions by: Elizabeth Craig +// Alex Kocharin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Disabling unified-signatures rule so different documentation can be provided for each signature. +// tslint:disable:unified-signatures + +export interface ParseOptions { + /** + * What to do with reserved keys (default 'ignore'). + * - "ignore" - ignore reserved keys + * - "throw" - throw SyntaxError in case of reserved keys + * - "replace" - replace reserved keys, this is the default JSON.parse behaviour, unsafe + */ + reserved_keys?: 'ignore' | 'throw' | 'replace'; + + /** + * Create object as `Object.create(null)` instead of `{}`. + * - If reserved_keys != 'replace', default is false. + * - If reserved_keys == 'replace', default is true. + * + * It is usually unsafe and not recommended to change this option to false in the last case. + */ + null_prototype?: boolean; + + /** + * Reviver function (follows the JSON spec). This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + reviver?: (key: any, value: any) => any; + + /** + * Operation mode (default 'json5'). Set to 'json' if you want to throw on non-strict json files. + */ + mode?: 'json5' | 'json' | 'cjson'; +} + +export interface StringifyOptions { + /** + * Output ascii only (default false). + * If this option is enabled, output will not have any characters except 0x20-0x7f. + */ + ascii?: boolean; + + /** + * This option follows JSON specification. + * @default '\t' + */ + indent?: string | number | boolean; + + /** + * Enquoting char. + * - If `mode` is 'json', default is " + * - Otherwise, default is ' + */ + quote?: '"' | "'"; + + /** + * Whether keys quoting in objects is required or not. + * If you want `{"q": 1}` instead of `{q: 1}`, set it to true. + * - If `mode` is 'json', default is true + * - Otherwise, default is false + */ + quote_keys?: boolean; + + /** + * Sort all keys while stringifying. + * By default sort order will depend on implementation--with v8 it's insertion order. + * If set to true, all keys (but not arrays) will be sorted alphabetically. + * You can provide your own sorting function as well. + * @default false + */ + sort_keys?: boolean | ((a: any, b: any) => number); + + /** + * Replacer function or array. This option follows JSON specification. + * If a function, used to transform the results. + * If an array, acts as a approved list for selecting the object properties that will be stringified. + */ + replacer?: ((key: string, value: any) => any) | Array; + + /** + * Don't output trailing comma. If this option is set, arrays like `[1,2,3,]` will never be generated. + * Otherwise they may be generated for pretty printing. + * - If `mode` is JSON, default is true + * - Otherwise, default is false + */ + no_trailing_comma?: boolean; + + /** + * Operation mode. Set it to 'json' if you want correct json in the output. + * If it is 'json', following options are implied: + * - options.quote = '"' + * - options.no_trailing_comma = true + * - options.quote_keys = true + * - '\x' literals are not used + */ + mode?: 'json' | 'json5' | 'cjson'; +} + +/** + * Represents a token in a JSON file. + */ +export interface Token { + /** Raw text of this token. If you join all raws, you will get the original document. */ + raw: string; + /** Type of the token. */ + type: 'whitespace' | 'comment' | 'key' | 'literal' | 'separator' | 'newline'; + /** Path to the current token in the syntax tree. */ + stack: string[]; + /** Value of the token if token is a key or literal. */ + value?: any; +} + +/** + * Object defining a programming style in which the JSON document was written. + */ +export interface JsonStyle { + /** Preferred indentation. */ + indent: string; + /** Preferred newline. */ + newline: string; + /** " or ' depending on which quote is preferred. */ + quote: string; + /** True if unquoted keys were used at least once. */ + quote_keys: boolean; + /** True if input has a whitespace token. */ + has_whitespace: boolean; + /** True if input has a comment token. */ + has_comments: boolean; + /** True if input has a newline token. */ + has_newlines: boolean; + /** True if input has at least one trailing comma. */ + has_trailing_comma: boolean; +} + +/** + * Parse json/json5 text and returns a javascript value it corresponds to. + * @param text Text to parse + * @param options Parser options + */ +export function parse(text: string, options?: ParseOptions): any; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ +export function parse(text: string, reviver?: (key: any, value: any) => any): any; + +/** + * Convert javascript value to an appropriate json/json5 text. + * @param value Value to serialize + * @param options Serializer options + */ +export function stringify(value: any, options?: StringifyOptions): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: Array | null, space?: string | number): string; + +/** + * Parse json/json5 text and return an array of tokens it consists of. + * @param text Text to tokenize + * @param options Parser options + */ +export function tokenize(text: string, options?: ParseOptions): Token[]; + +/** + * Parse json/json5 text and try to guess indentation, quoting style, etc. + * @param text Text to analyze + * @param options Parser options + */ +export function analyze(text: string, options?: ParseOptions): JsonStyle; + +/** + * Change json/json5 text, preserving original formatting as much as possible. + * @param text Original text + * @param new_value New value you want to set + * @param options Parser or stringifier options + * + * @example + * // here is your original JSON document: + * var input = '{"foo": "bar", "baz": 123}' + * + * // you need to parse it first: + * var json = jju.parse(input, {mode: 'json'}) + * // json is { foo: 'bar', baz: 123 } + * + * // then you can change it as you like: + * json.foo = 'quux' + * json.hello = 'world' + * + * // then you run an update function to change the original json: + * var output = jju.update(input, json, {mode: 'json'}) + * // output is '{"foo": "quux", "baz": 123, "hello": "world"}' + */ +export function update(text: string, new_value: any, options?: ParseOptions | StringifyOptions): string; diff --git a/types/jju/jju-tests.ts b/types/jju/jju-tests.ts new file mode 100644 index 0000000000..0de4d973b1 --- /dev/null +++ b/types/jju/jju-tests.ts @@ -0,0 +1,4 @@ +import * as jju from 'jju'; + +jju.parse('{}'); // $ExpectType any +jju.stringify({}); // $ExpectType string diff --git a/types/jju/tsconfig.json b/types/jju/tsconfig.json new file mode 100644 index 0000000000..08bb6638c7 --- /dev/null +++ b/types/jju/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", + "jju-tests.ts" + ] +} diff --git a/types/jju/tslint.json b/types/jju/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jju/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5068c7952765e6d19337c6fedaa58dba6195ff9d Mon Sep 17 00:00:00 2001 From: Elizabeth Craig Date: Wed, 28 Nov 2018 20:29:55 -0800 Subject: [PATCH 072/155] Allow parse and stringify options for update() --- types/jju/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jju/index.d.ts b/types/jju/index.d.ts index 46fbf2f77b..f8bf96d639 100644 --- a/types/jju/index.d.ts +++ b/types/jju/index.d.ts @@ -192,7 +192,7 @@ export function analyze(text: string, options?: ParseOptions): JsonStyle; * Change json/json5 text, preserving original formatting as much as possible. * @param text Original text * @param new_value New value you want to set - * @param options Parser or stringifier options + * @param options Parser and stringifier options * * @example * // here is your original JSON document: @@ -210,4 +210,4 @@ export function analyze(text: string, options?: ParseOptions): JsonStyle; * var output = jju.update(input, json, {mode: 'json'}) * // output is '{"foo": "quux", "baz": 123, "hello": "world"}' */ -export function update(text: string, new_value: any, options?: ParseOptions | StringifyOptions): string; +export function update(text: string, new_value: any, options?: ParseOptions & StringifyOptions): string; From 12b2403208f432eab01af6d45acd095fdcfb9ea6 Mon Sep 17 00:00:00 2001 From: Jessica Date: Thu, 29 Nov 2018 13:57:50 +0900 Subject: [PATCH 073/155] Simplify css attribute declaration, add jsdoc --- types/styled-components/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index ee64b37772..2f3b6b4ec5 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -454,6 +454,11 @@ declare module "react" { // nature of this declaration. // If you are writing this inline you already have access to all the attributes anyway, // no need for the extra indirection. - css?: import(".").CSSIntrinsicAttributeType; // tslint:disable-line whitespace + /** + * If present, this React element will be converted by + * `babel-plugin-styled-components` into a styled component + * with the given css as its styles. + */ + css?: CSSIntrinsicAttributeType; } } From f8a55ca2b6d82464c53dccbf01e75971ecdff5c0 Mon Sep 17 00:00:00 2001 From: taoqf Date: Thu, 29 Nov 2018 13:48:15 +0800 Subject: [PATCH 074/155] add definition baidu-app --- types/baidu-app/baidu-app-tests.ts | 2007 ++++++++++++ types/baidu-app/index.d.ts | 4758 ++++++++++++++++++++++++++++ types/baidu-app/tsconfig.json | 24 + types/baidu-app/tslint.json | 7 + 4 files changed, 6796 insertions(+) create mode 100644 types/baidu-app/baidu-app-tests.ts create mode 100644 types/baidu-app/index.d.ts create mode 100644 types/baidu-app/tsconfig.json create mode 100644 types/baidu-app/tslint.json diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个

; } + const myCss = 'background: blue;'; + return ( <>
-
-
+
+
+
+
"blue"}; @@ -808,7 +827,10 @@ function cssProp() { `} /> - + Date: Fri, 30 Nov 2018 12:01:59 +0100 Subject: [PATCH 089/155] [node] add some more elements to IncomingHttpHeaders --- types/node/index.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index f71cd9f6ec..b9edae0587 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1126,10 +1126,10 @@ declare module "http" { 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1139,14 +1139,24 @@ declare module "http" { 'content-location'?: string; 'content-range'?: string; 'content-type'?: string; + 'cookie'?: string; 'date'?: string; + 'expect'?: string; 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; 'last-modified'?: string; 'location'?: string; 'pragma'?: string; 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; 'public-key-pins'?: string; + 'range'?: string; 'referer'?: string; 'retry-after'?: string; 'set-cookie'?: string[]; From 0d6d7ce20fb6251e0af9fb871faf664ed7a48ee9 Mon Sep 17 00:00:00 2001 From: Jessica Date: Fri, 30 Nov 2018 20:32:32 +0900 Subject: [PATCH 090/155] Add missing file declaration --- types/styled-components/tsconfig.json | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/types/styled-components/tsconfig.json b/types/styled-components/tsconfig.json index 22af0d4a13..fb9b5a0f7b 100644 --- a/types/styled-components/tsconfig.json +++ b/types/styled-components/tsconfig.json @@ -3,20 +3,26 @@ "baseUrl": "../", "forceConsistentCasingInFileNames": true, "jsx": "react", - "lib": ["es6", "dom"], + "lib": [ + "es6", + "dom" + ], "module": "commonjs", "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, - "typeRoots": ["../"], + "typeRoots": [ + "../" + ], "types": [] }, "files": [ "index.d.ts", "macro.d.ts", + "cssprop.d.ts", "test/index.tsx", "test/macro.tsx" ] -} +} \ No newline at end of file From c5bc70efc08abdaebef17c425bbe9edbaf9cbd84 Mon Sep 17 00:00:00 2001 From: Jessica Date: Fri, 30 Nov 2018 20:35:04 +0900 Subject: [PATCH 091/155] Fix lint --- types/styled-components/index.d.ts | 10 +++++----- types/styled-components/test/index.tsx | 17 +++++++---------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 761c48a104..7007a3d829 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -440,21 +440,21 @@ export class StyleSheetManager extends React.Component< * The CSS prop is not declared by default in the types as it would cause 'css' to be present * on the types of anything that uses styled-components indirectly, even if they do not use the * babel plugin. - * + * * You can load a default declaration by using writing this special import from * a typescript file. This module does not exist in reality, which is why the {} is important: - * + * * ```ts * import {} from 'styled-components/cssprop' * ``` - * + * * Or you can declare your own module augmentation, which allows you to specify the type of Theme: - * + * * ```ts * import { CSSProp } from 'styled-components' * * interface MyTheme {} - * + * * declare module 'react' { * interface Attributes { * css?: CSSProp diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 43f0f68607..6e8715730e 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -783,15 +783,16 @@ function cssProp() { return
; } - const myCss = 'background: blue;'; + const myCss = "background: blue;"; return ( <>
-
+ {/* + For some reason $ExpectError doesn't work on this expression. + Only strings work, objects crash the plugin. +
+ */}
- Date: Fri, 30 Nov 2018 13:23:22 +0100 Subject: [PATCH 092/155] Remove Promise in Request.frame function The type definition of the Request class declares the return type of the frame() function as Promise, but it should be Frame | null only. --- types/puppeteer/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index cbb31f2fd0..d90f02f8b8 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -968,7 +968,7 @@ export interface Request { /** * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages */ - frame(): Promise; + frame(): Frame | null; /** * An object with HTTP headers associated with the request. From c83d99b2fe77138c5d67dfe33e566140a690a23e Mon Sep 17 00:00:00 2001 From: Toby Li Date: Fri, 30 Nov 2018 15:28:29 +0000 Subject: [PATCH 093/155] Corrected notification duration to timeout, state restored to nomal --- types/openfin/index.d.ts | 6 +++--- types/openfin/openfin-tests.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 55ee5b6741..78b1801b0b 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -420,7 +420,7 @@ declare namespace fin { /** * The timeout for displaying a notification.Can be in milliseconds or "never". */ - duration?: number | "never"; + timeout?: number | "never"; /** * The url of the notification */ @@ -804,9 +804,9 @@ declare namespace fin { */ getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; /** - * Gets the current state ("minimized", "maximized", or "restored") of the window. + * Gets the current state ("minimized", "maximized", or "normal") of the window. */ - getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void; /** * Returns the zoom level of the window. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 167a6c86be..e4430ff9c2 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -207,7 +207,7 @@ function test_notification() { notification.close(); // sendMessage notification = new fin.desktop.Notification({ - duration: 10, + timeout: 10, url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, From 4831c49ca4f685ebca669b9e7a3944620689705d Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Fri, 30 Nov 2018 17:15:51 +0100 Subject: [PATCH 094/155] [postcss-url] add typings --- types/postcss-url/index.d.ts | 148 +++++++++++++++++++++++++ types/postcss-url/package.json | 6 + types/postcss-url/postcss-url-tests.ts | 17 +++ types/postcss-url/tsconfig.json | 23 ++++ types/postcss-url/tslint.json | 1 + 5 files changed, 195 insertions(+) create mode 100644 types/postcss-url/index.d.ts create mode 100644 types/postcss-url/package.json create mode 100644 types/postcss-url/postcss-url-tests.ts create mode 100644 types/postcss-url/tsconfig.json create mode 100644 types/postcss-url/tslint.json diff --git a/types/postcss-url/index.d.ts b/types/postcss-url/index.d.ts new file mode 100644 index 0000000000..361b69f1c7 --- /dev/null +++ b/types/postcss-url/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for postcss-url 8.0 +// Project: https://github.com/postcss/postcss-url +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { Plugin } from 'postcss'; + +declare namespace url { + type CustomTransformFunction = ( + asset: { + /** + * Original URL. + */ + url: string; + + /** + * URL pathname. + */ + pathname?: string; + + /** + * Absolute path to asset. + */ + absolutePath?: string; + + /** + * Current relative path to asset. + */ + relativePath?: string; + + /** + * Querystring from URL. + */ + search?: string; + + /** + * Hash from URL. + */ + hash?: string; + }, + dir: { + /** + * PostCSS from option. + */ + from?: string; + + /** + * PostCSS to option. + */ + to?: string; + + /** + * File path. + */ + file?: string; + }, + ) => string; + type CustomHashFunction = (file: Buffer) => string; + type CustomFilterFunction = (file: string) => boolean; + + interface Options { + /** + * URL rewriting mechanism. + * + * @default 'rebase' + */ + url?: 'copy' | 'inline' | 'rebase' | CustomTransformFunction; + + /** + * Specify the maximum file size to inline (in kilobytes). + */ + maxSize?: number; + + /** + * Do not warn when an SVG URL with a fragment is inlined. + * PostCSS-URL does not support partial inlining. + * The entire SVG file will be inlined. + * By default a warning will be issued when this occurs. + * + * @default false + */ + ignoreFragmentWarning?: boolean; + + /** + * Determine wether a file should be inlined. + */ + filter?: RegExp | CustomFilterFunction | string; + + /** + * Specifies whether the URL's fragment identifer value, if present, will be added to the inlined data URI. + * + * @default false + */ + includeUriFragment?: boolean; + + /** + * The fallback method to use if the maximum size is exceeded or the URL contains a hash. + */ + fallback?: CustomTransformFunction; + + /** + * Specify the base path or list of base paths where to search images from. + */ + basePath?: string | string[]; + + /** + * The assets files will be copied in that destination. + * + * @default false + */ + assetsPath?: boolean | string; + + /** + * Rename the path of the files by a hash name. + * + * @default false + */ + useHash?: boolean; + + /** + * Hash options + */ + hashOptions?: { + /** + * Hashing method or custom function. + */ + method?: 'xxhash32' | 'xxhash64' | CustomHashFunction; + + /** + * Shrink hast to certain length. + */ + shrink?: number; + + /** + * Append the original filename in resulting filename. + */ + append?: boolean; + }; + } + + type Url = Plugin; +} + +declare const url: url.Url; +export = url; diff --git a/types/postcss-url/package.json b/types/postcss-url/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-url/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-url/postcss-url-tests.ts b/types/postcss-url/postcss-url-tests.ts new file mode 100644 index 0000000000..a258b49be4 --- /dev/null +++ b/types/postcss-url/postcss-url-tests.ts @@ -0,0 +1,17 @@ +import * as postcss from 'postcss'; +import * as url from 'postcss-url'; + +const standard: postcss.Transformer = url(); + +const single: postcss.Transformer = url({ url: 'copy', assetsPath: 'img', useHash: true }); + +const multiple: postcss.Transformer = url([ + { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true }, + { filter: '**/assets/inline/*.svg', url: 'inline' }, + { filter: '**/assets/**/*.gif', url: 'rebase' }, + { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }, +]); + +postcss().use(standard); +postcss().use(single); +postcss().use(multiple); diff --git a/types/postcss-url/tsconfig.json b/types/postcss-url/tsconfig.json new file mode 100644 index 0000000000..c7759ba2d3 --- /dev/null +++ b/types/postcss-url/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", + "postcss-url-tests.ts" + ] +} diff --git a/types/postcss-url/tslint.json b/types/postcss-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3c08522763fab883305b539e8a66d1589a908c11 Mon Sep 17 00:00:00 2001 From: Gilad Peleg Date: Fri, 30 Nov 2018 18:46:24 +0200 Subject: [PATCH 095/155] Gravatar can accept optional html img attributes --- types/react-gravatar/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index b2962edc8d..56e48b3b9b 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -25,7 +25,7 @@ declare namespace Gravatar { type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; type Rating = "g" | "pg" | "r" | "x"; - interface Props { + interface Props extends Partial { /** * The email address used to look up the Gravatar image. * If you wish to avoid sending an email address to the client, you can compute the md5 hash on the server and From 65430a8a7b530420437b8f618849663dbef2d004 Mon Sep 17 00:00:00 2001 From: James Ide Date: Fri, 30 Nov 2018 10:17:33 -0800 Subject: [PATCH 096/155] [react-native] Make requireNativeComponent work with an update to @types/react 4dd9510a504875fb79a399d468e8f39e892af617 changed `React.ReactType` to look at entries in the `JSX.IntrinsicElements` map, which caused rendering `React.ReactType` elements to fail. This commit fixes the RN type declarations by returning `any`. We don't care about the actual return type that much -- it's concretely a string but externally, as a user of react-native, you'd want to only use it as a JSX component type and not as a string. And since it's a string that isn't registered with `JSX.IntrinsicElements`, there's no extra type information (ex: list of valid props) associated with it. Longer term, it might make sense for `@types/react-native` to add native component types like `RCTView` to `JSX.IntrinsicElements` and go back to using `React.ReactType<'RCTView'>` with `requireNativeComponent`, but this is a disruptive change. Test plan: Ran tests, verified they pass again. Fixes #30958. --- types/react-native/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 6e54b6d7c9..ae1aa35f00 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -9037,8 +9037,11 @@ export const PixelRatio: PixelRatioStatic; * * const View = requireNativeComponent('RCTView'); * + * The concrete return type of `requireNativeComponent` is a string, but the declared type is + * `any` because TypeScript assumes anonymous JSX intrinsics (`string` instead of `"div", for + * example) not to have any props. */ -export function requireNativeComponent(viewName: string): React.ReactType; +export function requireNativeComponent(viewName: string): any; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass From a386b24578934f1be2128e0f695485bd78a84f56 Mon Sep 17 00:00:00 2001 From: Fabio Tea Date: Fri, 30 Nov 2018 19:48:40 +0100 Subject: [PATCH 097/155] url-assembler: making 'strict: boolean' parameter of param functions optional as per api-definition of 1.2.10 --- types/url-assembler/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/url-assembler/index.d.ts b/types/url-assembler/index.d.ts index 3f33bf921a..e27fbbe58d 100644 --- a/types/url-assembler/index.d.ts +++ b/types/url-assembler/index.d.ts @@ -7,8 +7,8 @@ interface UrlAssembler { template(template: string): UrlAssembler; prefix(subPath: string): UrlAssembler; segment(subPathTemplate: string): UrlAssembler; - param(key: string, value: string, strict: boolean): UrlAssembler; - param(params: {[s: string]: any}, strict: boolean): UrlAssembler; + param(key: string, value: string, strict?: boolean): UrlAssembler; + param(params: {[s: string]: any}, strict?: boolean): UrlAssembler; query(key: string, value: any): UrlAssembler; query(params: {[s: string]: any}): UrlAssembler; toString(): string; From 8814139174714997d92831b3a41a3f9eee376fa4 Mon Sep 17 00:00:00 2001 From: Fabio Tea Date: Fri, 30 Nov 2018 19:56:58 +0100 Subject: [PATCH 098/155] [url-assembler]: making 'strict: boolean' parameter optional (+adjusted version comment) --- types/url-assembler/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/url-assembler/index.d.ts b/types/url-assembler/index.d.ts index e27fbbe58d..bce3adb35e 100644 --- a/types/url-assembler/index.d.ts +++ b/types/url-assembler/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for url-assembler 1.2 +// Type definitions for url-assembler 1.2.10 // Project: https://github.com/Floby/node-url-assembler // Definitions by: Wolfgang Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 3dc3584b476342f732bdba4cb8612ff3d4113b62 Mon Sep 17 00:00:00 2001 From: Fabio Tea Date: Fri, 30 Nov 2018 21:07:18 +0100 Subject: [PATCH 099/155] [url-assembler]: fixed dt-header (removed patch-version) --- types/url-assembler/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/url-assembler/index.d.ts b/types/url-assembler/index.d.ts index bce3adb35e..e27fbbe58d 100644 --- a/types/url-assembler/index.d.ts +++ b/types/url-assembler/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for url-assembler 1.2.10 +// Type definitions for url-assembler 1.2 // Project: https://github.com/Floby/node-url-assembler // Definitions by: Wolfgang Faust // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 30a14bb78ef80d38789c512debb8b8fa185c6846 Mon Sep 17 00:00:00 2001 From: Mark Wolff Date: Fri, 30 Nov 2018 14:03:07 -0800 Subject: [PATCH 100/155] Update docs comment for start/stoptrackpage --- types/applicationinsights-js/index.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index b86dc23634..ee509a0eb5 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -670,13 +670,15 @@ declare module Microsoft.ApplicationInsights { context: ITelemetryContext; queue: Array<() => void>; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops, + * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view + * and send the event. * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. */ startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. + * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements. + * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`. * @param name The string you used as the name in startTrackPage. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. From efbcbdebaf39c27edb7681c8a666a1d451982a6f Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Fri, 30 Nov 2018 17:26:52 -0500 Subject: [PATCH 101/155] Revert "react: Improve type checking of component static properties. (#30730)" (#30964) This reverts commit 5610636ad2e5dbf618f1ed8db8acb4d0407305a6. --- .../components/responsive.d.ts | 30 +++ types/react-select/lib/components/Menu.d.ts | 6 + .../test/examples/CustomNoOptionsMessage.tsx | 7 +- types/react-virtualized/dist/es/List.d.ts | 2 +- types/react-virtualized/dist/es/Table.d.ts | 79 ++++++- types/react/index.d.ts | 126 +++-------- types/react/test/managedAttributes.tsx | 208 ++++++++---------- types/theming/index.d.ts | 2 +- 8 files changed, 235 insertions(+), 225 deletions(-) diff --git a/types/react-foundation/components/responsive.d.ts b/types/react-foundation/components/responsive.d.ts index 9b3a8361ed..94a915f2c8 100644 --- a/types/react-foundation/components/responsive.d.ts +++ b/types/react-foundation/components/responsive.d.ts @@ -24,6 +24,36 @@ export declare class ResponsiveNavigation extends Component; + alignX: PropTypes.Requireable; + alignY: PropTypes.Requireable; + selfAlignX: PropTypes.Requireable; + selfAlignY: PropTypes.Requireable; + centerAlign: PropTypes.Requireable; + flexContainer: PropTypes.Requireable; + flexDirRow: PropTypes.Requireable; + flexDirRowRev: PropTypes.Requireable; + flexDirCol: PropTypes.Requireable; + flexDirColRev: PropTypes.Requireable; + flexChild: PropTypes.Requireable; + flexOrder: PropTypes.Requireable; + flexOrderSmall: PropTypes.Requireable; + flexOrderMedium: PropTypes.Requireable; + flexOrderLarge: PropTypes.Requireable; + showFor: PropTypes.Requireable; + showOnlyFor: PropTypes.Requireable; + hideFor: PropTypes.Requireable; + hideOnlyFor: PropTypes.Requireable; + isHidden: PropTypes.Requireable; + isInvisible: PropTypes.Requireable; + showForLandscape: PropTypes.Requireable; + showForPortrait: PropTypes.Requireable; + showForSr: PropTypes.Requireable; + showOnFocus: PropTypes.Requireable; + isClearfix: PropTypes.Requireable; + float: PropTypes.Requireable; + }; static defaultProps: { breakpoint: number; }; diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts index 8c6e5fb6c8..387b538882 100644 --- a/types/react-select/lib/components/Menu.d.ts +++ b/types/react-select/lib/components/Menu.d.ts @@ -67,6 +67,9 @@ export type MenuProps = CommonProps & { export function menuCSS(state: MenuState): React.CSSProperties; export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getPlacement: (ref: ElementRef) => void; getState: () => MenuProps & MenuState; } @@ -143,6 +146,9 @@ interface PortalStyleArgs { export function menuPortalCSS(args: PortalStyleArgs): React.CSSProperties; export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getChildContext(): { getPortalPlacement: (state: MenuState) => void; }; diff --git a/types/react-select/test/examples/CustomNoOptionsMessage.tsx b/types/react-select/test/examples/CustomNoOptionsMessage.tsx index 3896272d5b..6bea4cb47a 100644 --- a/types/react-select/test/examples/CustomNoOptionsMessage.tsx +++ b/types/react-select/test/examples/CustomNoOptionsMessage.tsx @@ -18,12 +18,7 @@ const NoOptionsMessage = (props: any) => { export default class CustomNoOptionsMessage extends React.Component { render() { return ( - // Without the type argument, `OptionType` is inferred as `never` from the - // `options` attribute of type `never[]`, and `Select.defaultProps` (of - // type `Props`) fails to be assignable to the instantiated props - // type, `Props`. This issue shouldn't come up in real code where - // the `options` attribute isn't a literal empty array. - +