diff --git a/README.md b/README.md index 4343577bd0..bbf2a6f16e 100644 --- a/README.md +++ b/README.md @@ -255,12 +255,30 @@ Here are the [currently requested definitions](https://github.com/DefinitelyType If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`. +#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? + +Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. + +Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: + +> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct + +This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. +This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. + +It is more appropriate to import the module using the `import foo = require("foo");` syntax. +Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options: +- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm). +- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7). + #### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`? -If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project. -Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option. +Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) +or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) +compiler options. + Do not change the type definition if it is accurate. -For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export. +For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module. #### I want to use features from TypeScript 2.1 or above. @@ -268,8 +286,9 @@ Then you will have to add a comment to the last line of your definition header ( #### I want to use features from TypeScript 3.1 or above. -You will need to use the `typesVersions` feature of TypeScript 3.1 and above. You can find a detailed explanation -of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions). +You can use the same `// TypeScript Version: 3.1` comment as above. +However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above. +You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions). Here's a short explanation to get you started: @@ -368,19 +387,6 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead. -#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? - -Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. - -Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: - -> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct - -This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. -This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. - -It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such. - ## License This project is licensed under the MIT license. diff --git a/types/asn1/asn1-tests.ts b/types/asn1/asn1-tests.ts new file mode 100644 index 0000000000..f37541b03e --- /dev/null +++ b/types/asn1/asn1-tests.ts @@ -0,0 +1,88 @@ +import { Ber, BerReader, BerWriter } from 'asn1'; + +let buf: Buffer = Buffer.alloc(0); +let bool = false; +let str = ''; +let num = 0; +let numOrNull: number | null = 0; +const roStrArray: ReadonlyArray = [str]; + +const reader = new BerReader(buf); +numOrNull = reader.peek(); +bool = reader.readBoolean(); +numOrNull = reader.readByte(bool); +num = reader.readEnumeration(); +num = reader.readInt(); +num = reader.readLength(); +num = reader.readLength(num); +str = reader.readOID(); +str = reader.readOID(num); +numOrNull = reader.readSequence(); +numOrNull = reader.readSequence(num); +str = reader.readString(); +str = reader.readString(num); +buf = reader.readString(num, bool); +num = reader._readTag(); +num = reader._readTag(num); + +let writer = new BerWriter(); +writer = new BerWriter({ + size: num, + growthFactor: num, +}); + +buf = writer.buffer; +buf = writer._buf; +num = writer._size; +num = writer._offset; + +writer.endSequence(); +writer.startSequence(); +writer.startSequence(num); +writer.writeBoolean(bool); +writer.writeBoolean(bool, num); +writer.writeBuffer(buf, num); +writer.writeByte(num); +writer.writeEnumeration(num); +writer.writeEnumeration(num, num); +writer.writeInt(num); +writer.writeInt(num, num); +writer.writeLength(num); +writer.writeNull(); +writer.writeOID(str, num); +writer.writeString(str); +writer.writeString(str, num); +writer.writeStringArray(roStrArray); +writer._ensure(num); + +num = Ber.BMPString; +num = Ber.BitString; +num = Ber.Boolean; +num = Ber.CharacterString; +num = Ber.Constructor; +num = Ber.Context; +num = Ber.EOC; +num = Ber.Enumeration; +num = Ber.External; +num = Ber.GeneralString; +num = Ber.GeneralizedTime; +num = Ber.GraphicString; +num = Ber.IA5String; +num = Ber.Integer; +num = Ber.Null; +num = Ber.NumericString; +num = Ber.OID; +num = Ber.ObjectDescriptor; +num = Ber.OctetString; +num = Ber.PDV; +num = Ber.PrintableString; +num = Ber.Real; +num = Ber.RelativeOID; +num = Ber.Sequence; +num = Ber.Set; +num = Ber.T61String; +num = Ber.UTCTime; +num = Ber.UniversalString; +num = Ber.Utf8String; +num = Ber.VideotexString; +num = Ber.VisibleString; diff --git a/types/asn1/index.d.ts b/types/asn1/index.d.ts new file mode 100644 index 0000000000..3f7de44af8 --- /dev/null +++ b/types/asn1/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for asn1 0.2 +// Project: https://github.com/joyent/node-asn1 +// Definitions by: Jim Geurts +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +export class BerReader { + readonly buffer: Buffer; + readonly offset: number; + readonly length: number; + readonly remain: number; + readonly _buf: Buffer; + _size: number; + _offset: number; + + constructor(data: Buffer); + + peek(): number | null; + readBoolean(): boolean; + readByte(peek: boolean): number | null; + readEnumeration(): number; + readInt(): number; + readLength(offset?: number): number; + readOID(tag?: number): string; + readSequence(tag?: number): number | null; + readString(tag?: number): string; + readString(tag: number, retbuf: boolean): Buffer; + _readTag(tag?: number): number; +} + +export class BerWriter { + readonly buffer: Buffer; + readonly _buf: Buffer; + readonly _size: number; + _offset: number; + + constructor(options?: { + size: number; + growthFactor: number; + }); + + endSequence(): void; + startSequence(tag?: number): void; + writeBoolean(b: boolean, tag?: number): void; + writeBuffer(buf: Buffer, tag: number): void; + writeByte(b: number): void; + writeEnumeration(i: number, tag?: number): void; + writeInt(i: number, tag?: number): void; + writeLength(len: number): void; + writeNull(): void; + writeOID(s: string, tag: number): void; + writeString(s: string, tag?: number): void; + writeStringArray(strings: ReadonlyArray): void; + _ensure(length: number): void; +} + +export namespace Ber { + const BMPString: number; + const BitString: number; + const Boolean: number; + const CharacterString: number; + const Constructor: number; + const Context: number; + const EOC: number; + const Enumeration: number; + const External: number; + const GeneralString: number; + const GeneralizedTime: number; + const GraphicString: number; + const IA5String: number; + const Integer: number; + const Null: number; + const NumericString: number; + const OID: number; + const ObjectDescriptor: number; + const OctetString: number; + const PDV: number; + const PrintableString: number; + const Real: number; + const RelativeOID: number; + const Sequence: number; + const Set: number; + const T61String: number; + const UTCTime: number; + const UniversalString: number; + const Utf8String: number; + const VideotexString: number; + const VisibleString: number; +} +/* +declare enum BerType { + EOC = 0, + Boolean = 1, + Integer = 2, + BitString = 3, + OctetString = 4, + Null = 5, + OID = 6, + ObjectDescriptor = 7, + External = 8, + Real = 9, // float + Enumeration = 10, + PDV = 11, + Utf8String = 12, + RelativeOID = 13, + Sequence = 16, + Set = 17, + NumericString = 18, + PrintableString = 19, + T61String = 20, + VideotexString = 21, + IA5String = 22, + UTCTime = 23, + GeneralizedTime = 24, + GraphicString = 25, + VisibleString = 26, + GeneralString = 28, + UniversalString = 29, + CharacterString = 30, + BMPString = 31, + Constructor = 32, + Context = 128, +} + +*/ diff --git a/types/asn1/tsconfig.json b/types/asn1/tsconfig.json new file mode 100644 index 0000000000..fd1bdc45d9 --- /dev/null +++ b/types/asn1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedParameters": true, + + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asn1-tests.ts" + ] +} \ No newline at end of file diff --git a/types/asn1/tslint.json b/types/asn1/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/asn1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index a38c928333..4fcbb5df33 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -812,6 +812,8 @@ export interface AuthorizeOptions { login_hint?: string; prompt?: string; mode?: "login" | "signUp"; + accessType?: string; + approvalPrompt?: string; } export interface CheckSessionOptions extends AuthorizeOptions { diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 92f0a6999b..ba6ebdc5ac 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1056,3 +1056,113 @@ const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = ( ] }); }; + +declare let lexEvent: AWSLambda.LexEvent; +lexEvent = { + currentIntent: { + name: 'intent-name', + slots: { + slot1: null, + slot2: 'value2', + }, + slotDetails: { + slot1: { + resolutions: [ + { value: 'value1' }, + ], + originalValue: 'originalValue', + } + }, + confirmationStatus: 'None', + }, + bot: { + name: 'bot name', + alias: 'bot alias', + version: 'bot version', + }, + userId: 'User ID specified in the POST request to Amazon Lex.', + inputTranscript: 'Text used to process the request', + invocationSource: 'FulfillmentCodeHook', + outputDialogMode: 'Text', + messageVersion: '1.0', + sessionAttributes: { + key1: 'value1', + key2: 'value2', + }, + requestAttributes: { + key1: 'value1', + key2: 'value2', + } +}; + +declare let lexResult: AWSLambda.LexResult; +declare let lexDialogAction: AWSLambda.LexDialogAction; +declare let lexDialogActionBase: AWSLambda.LexDialogActionBase; +declare let lexDialogActionClose: AWSLambda.LexDialogActionClose; +declare let lexDialogActionConfirmIntent: AWSLambda.LexDialogActionConfirmIntent; +declare let lexDialogActionDelegate: AWSLambda.LexDialogActionDelegate; +declare let lexDialogActionElicitIntent: AWSLambda.LexDialogActionElicitIntent; +declare let lexDialogActionElicitSlot: AWSLambda.LexDialogActionElicitSlot; +declare let lexGenericAttachment: AWSLambda.LexGenericAttachment; + +lexResult = { + sessionAttributes: { + attrib1: 'Value One', + }, + dialogAction: { + type: 'Close', + fulfillmentState: 'Failed', + }, +}; + +str = lexGenericAttachment.title; +str = lexGenericAttachment.subTitle; +str = lexGenericAttachment.imageUrl; +str = lexGenericAttachment.attachmentLinkUrl; +str = lexGenericAttachment.buttons[0].text; +str = lexGenericAttachment.buttons[0].value; + +lexDialogAction.type === 'Close'; +lexDialogAction.type === 'ConfirmIntent'; +lexDialogAction.type === 'Delegate'; +lexDialogAction.type === 'ElicitIntent'; +lexDialogAction.type === 'ElicitSlot'; + +lexDialogActionBase.message!.contentType === 'CustomPayload'; +lexDialogActionBase.message!.contentType === 'PlainText'; +lexDialogActionBase.message!.contentType === 'SSML'; +str = lexDialogActionBase.message!.content; +num = lexDialogActionBase.responseCard!.version; +lexDialogActionBase.responseCard!.contentType === 'application/vnd.amazonaws.card.generic'; +// $ExpectType LexGenericAttachment +lexDialogActionBase.responseCard!.genericAttachments[0]; + +lexDialogActionClose.type === 'Close'; +lexDialogActionClose.fulfillmentState === 'Failed'; +lexDialogActionClose.fulfillmentState === 'Fulfilled'; + +lexDialogActionConfirmIntent.type === 'ConfirmIntent'; +str = lexDialogActionConfirmIntent.intentName; +strOrNull = lexDialogActionConfirmIntent.slots['example']; + +lexDialogActionDelegate.type === 'Delegate'; +strOrNull = lexDialogActionDelegate.slots['example']; + +lexDialogActionElicitIntent.type === 'ElicitIntent'; +lexDialogActionElicitSlot.type === 'ElicitSlot'; +strOrNull = lexDialogActionElicitSlot.slots['example']; +str = lexDialogActionElicitSlot.slotToElicit; +str = lexDialogActionElicitSlot.intentName; + +const lexEventHandler: AWSLambda.LexHandler = async ( + event: AWSLambda.LexEvent, + context: AWSLambda.Context, +) => { + // $ExpectType LexEvent + event; + + // $ExpectType Context + context; + str = context.functionName; + return lexResult; +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 4cafe3d2da..52314529bc 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -876,6 +876,100 @@ export interface SQSMessageAttributes { [name: string]: SQSMessageAttribute; } +// Lex +// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-lex +export interface LexEvent { + currentIntent: { + name: string; + slots: { [name: string]: string | null }; + slotDetails: LexSlotDetails; + confirmationStatus: 'None' | 'Confirmed' | 'Denied'; + }; + bot: { + name: string; + alias: string; + version: string; + }; + userId: string; + inputTranscript: string; + invocationSource: 'DialogCodeHook' | 'FulfillmentCodeHook'; + outputDialogMode: 'Text' | 'Voice'; + messageVersion: '1.0'; + sessionAttributes: { [key: string]: string }; + requestAttributes: { [key: string]: string } | null; +} + +export interface LexSlotResolution { + value: string; +} + +export interface LexSlotDetails { + [name: string]: { + // The following line only works in TypeScript Version: 3.0, The array should have at least 1 and no more than 5 items + // resolutions: [LexSlotResolution, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?]; + resolutions: LexSlotResolution[] + originalValue: string; + }; +} + +export interface LexGenericAttachment { + title: string; + subTitle: string; + imageUrl: string; + attachmentLinkUrl: string; + buttons: Array<{ + text: string; + value: string; + }>; +} + +export interface LexDialogActionBase { + type: 'Close' | 'ElicitIntent' | 'ElicitSlot' | 'ConfirmIntent'; + message?: { + contentType: 'PlainText' | 'SSML' | 'CustomPayload'; + content: string; + }; + responseCard?: { + version: number; + contentType: 'application/vnd.amazonaws.card.generic'; + genericAttachments: LexGenericAttachment[]; + }; +} + +export interface LexDialogActionClose extends LexDialogActionBase { + type: 'Close'; + fulfillmentState: 'Fulfilled' | 'Failed'; +} + +export interface LexDialogActionElicitIntent extends LexDialogActionBase { + type: 'ElicitIntent'; +} + +export interface LexDialogActionElicitSlot extends LexDialogActionBase { + type: 'ElicitSlot'; + intentName: string; + slots: { [name: string]: string | null }; + slotToElicit: string; +} + +export interface LexDialogActionConfirmIntent extends LexDialogActionBase { + type: 'ConfirmIntent'; + intentName: string; + slots: { [name: string]: string | null }; +} + +export interface LexDialogActionDelegate { + type: 'Delegate'; + slots: { [name: string]: string | null }; +} + +export type LexDialogAction = LexDialogActionClose | LexDialogActionElicitIntent | LexDialogActionElicitSlot | LexDialogActionConfirmIntent | LexDialogActionDelegate; + +export interface LexResult { + sessionAttributes?: { [key: string]: string }; + dialogAction: LexDialogAction; +} + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -938,6 +1032,9 @@ export type ScheduledHandler = Handler; // TODO: Alexa +export type LexHandler = Handler; +export type LexCallback = Callback; + export type APIGatewayProxyHandler = Handler; export type APIGatewayProxyCallback = Callback; export type ProxyHandler = APIGatewayProxyHandler; // Old name diff --git a/types/axios-case-converter/axios-case-converter-tests.ts b/types/axios-case-converter/axios-case-converter-tests.ts new file mode 100644 index 0000000000..77fa927976 --- /dev/null +++ b/types/axios-case-converter/axios-case-converter-tests.ts @@ -0,0 +1,6 @@ +import axios from "axios"; +import applyConverters from "axios-case-converter"; + +applyConverters(); // $ExpectError + +applyConverters(axios.create()); // $ExpectType AxiosInstance diff --git a/types/axios-case-converter/index.d.ts b/types/axios-case-converter/index.d.ts new file mode 100644 index 0000000000..2071ee4dbc --- /dev/null +++ b/types/axios-case-converter/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for axios-case-converter 0.3 +// Project: https://github.com/mpyw/axios-case-converter +// Definitions by: Derek Kniffin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { AxiosInstance } from "axios"; + +export default function applyConverters(axios: AxiosInstance): AxiosInstance; diff --git a/types/axios-case-converter/package.json b/types/axios-case-converter/package.json new file mode 100644 index 0000000000..ab98e74e0b --- /dev/null +++ b/types/axios-case-converter/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "axios": "^0.16.1" + } +} diff --git a/types/axios-case-converter/tsconfig.json b/types/axios-case-converter/tsconfig.json new file mode 100644 index 0000000000..fb3102b6eb --- /dev/null +++ b/types/axios-case-converter/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", + "axios-case-converter-tests.ts" + ] +} diff --git a/types/axios-case-converter/tslint.json b/types/axios-case-converter/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/axios-case-converter/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index dddd69bea8..f5a6c0e070 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -69,3 +69,12 @@ trans.default('name'); trans.deferred('name'); trans.immediate('name'); trans.exclusive('name'); + +const transTyped = db.transaction((param: number) => stmt.all(param)); +transTyped(1); +trans.default(1); +trans.deferred(1); +trans.immediate(1); +trans.exclusive(1); +// $ExpectError +transTyped('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 2c027ff6e6..32a71d96af 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -4,10 +4,17 @@ // Mathew Rumsey // Santiago Aguilar // Alessandro Vergani +// Andrew Kaiser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 import Integer = require("integer"); +type VariableArgFunction = (...params: any[]) => any; +type ArgumentTypes = F extends (...args: infer A) => any + ? A + : never; + declare namespace BetterSqlite3 { interface Statement { database: Database; @@ -34,12 +41,12 @@ declare namespace BetterSqlite3 { type: string | null; } - interface Transaction { - (...params: any[]): any; - default(...params: any[]): any; - deferred(...params: any[]): any; - immediate(...params: any[]): any; - exclusive(...params: any[]): any; + interface Transaction { + (...params: ArgumentTypes): any; + default(...params: ArgumentTypes): any; + deferred(...params: ArgumentTypes): any; + immediate(...params: ArgumentTypes): any; + exclusive(...params: ArgumentTypes): any; } interface Database { @@ -50,7 +57,7 @@ declare namespace BetterSqlite3 { inTransaction: boolean; prepare(source: string): Statement; - transaction(fn: (...params: any[]) => any): Transaction; + transaction(fn: F): Transaction; exec(source: string): this; pragma(source: string, options?: Database.PragmaOptions): any; checkpoint(databaseName?: string): this; @@ -113,7 +120,7 @@ declare namespace Database { type SqliteError = typeof SqliteError; type Statement = BetterSqlite3.Statement; type ColumnDefinition = BetterSqlite3.ColumnDefinition; - type Transaction = BetterSqlite3.Transaction; + type Transaction = BetterSqlite3.Transaction; type Database = BetterSqlite3.Database; } diff --git a/types/btoa/btoa-tests.ts b/types/btoa/btoa-tests.ts index d09cdad23a..7ce230fcf7 100644 --- a/types/btoa/btoa-tests.ts +++ b/types/btoa/btoa-tests.ts @@ -1,3 +1,3 @@ -import btoa from 'btoa'; +import btoa = require('btoa'); btoa('foo'); diff --git a/types/btoa/index.d.ts b/types/btoa/index.d.ts index cc311ed836..bdb02b5b59 100644 --- a/types/btoa/index.d.ts +++ b/types/btoa/index.d.ts @@ -1,7 +1,10 @@ // Type definitions for btoa 1.2 // Project: https://git.coolaj86.com/coolaj86/btoa.js // Definitions by: John Wright +// Alex Brick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -export default function(str: string): string; +declare function btoa(str: string): string; + +export = btoa; diff --git a/types/buble/buble-tests.ts b/types/buble/buble-tests.ts index e786ee6854..cebb373415 100644 --- a/types/buble/buble-tests.ts +++ b/types/buble/buble-tests.ts @@ -8,7 +8,7 @@ const input = 'const answer = () => 42;'; console.log(output.code); console.log(output.map.toString()); - console.log(output.map.toUrl); + console.log(output.map.toUrl()); })(); // Transform for Chrome & Firefox diff --git a/types/buble/index.d.ts b/types/buble/index.d.ts index c222d08e87..db3cb0a7b7 100644 --- a/types/buble/index.d.ts +++ b/types/buble/index.d.ts @@ -1,7 +1,10 @@ // Type definitions for buble 0.19 // Project: https://github.com/Rich-Harris/buble#README -// Definitions by: Kocal +// Definitions by: Hugo Alliaume // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { SourceMap } from "magic-string"; export interface TransformOptions { // source: https://github.com/Rich-Harris/buble/blob/master/src/support.js @@ -56,10 +59,7 @@ export interface TransformOptions { export interface TransformOutput { code: string; - map: { - toString(): string; - toUrl(): string; - }; + map: SourceMap; } export function transform(content: string, options?: TransformOptions): TransformOutput; diff --git a/types/react-bootstrap-typeahead/package.json b/types/buble/package.json similarity index 61% rename from types/react-bootstrap-typeahead/package.json rename to types/buble/package.json index e6696d08e7..d2f8119c0a 100644 --- a/types/react-bootstrap-typeahead/package.json +++ b/types/buble/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "csstype": "^2.2.0" + "magic-string": "^0.25.0" } } diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index b2fb68d4d7..bbafa0301c 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -585,6 +585,11 @@ declare namespace Bull { */ getJobCounts(): Promise; + /** + * Returns a promise that resolves with the job counts for the given queue of the given types. + */ + getJobCountByTypes(types: string[] | string): Promise; + /** * Returns a promise that resolves with the quantity of completed jobs. */ diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index bafed6edf8..eaa1a509d5 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -127,7 +127,7 @@ declare class ByteBuffer * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. */ static calculateUTF8Chars( str: string ): number; - + /** * Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes. */ @@ -574,6 +574,11 @@ declare class ByteBuffer */ writeInt8( value: number, offset?: number ): ByteBuffer; + /** + * Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64. + */ + writeLong( value: number | Long, offset?: number ): ByteBuffer; + /** * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. */ diff --git a/types/cacheable-request/cacheable-request-tests.ts b/types/cacheable-request/cacheable-request-tests.ts new file mode 100644 index 0000000000..95458c14b7 --- /dev/null +++ b/types/cacheable-request/cacheable-request-tests.ts @@ -0,0 +1,28 @@ +import * as http from 'http'; +import * as https from 'https'; +import CacheableRequest = require('cacheable-request'); +import QuickLRU = require('quick-lru'); + +// You can do +let cacheableRequest = new CacheableRequest(http.request); +const cacheReq = cacheableRequest('http://example.com', res => { + res; // $ExpectType ServerResponse | ResponseLike +}); +cacheReq.on('request', req => req.end()); + +cacheableRequest = new CacheableRequest(https.request); + +cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); +cacheableRequest = new CacheableRequest(http.request, new Map()); +cacheableRequest = new CacheableRequest(http.request, new QuickLRU({ maxSize: 1000 })); + +cacheableRequest('example.com', res => { + res; // $ExpectType ServerResponse | ResponseLike +}) + .on('error', err => { + err; // $ExpectType RequestErrorCls | CacheErrorCls + }) + .on('request', req => { + req.on('error', () => {}); + req.end(); + }); diff --git a/types/cacheable-request/index.d.ts b/types/cacheable-request/index.d.ts new file mode 100644 index 0000000000..98d858d3f6 --- /dev/null +++ b/types/cacheable-request/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { request, RequestOptions, ClientRequest, ServerResponse } from 'http'; +import { URL } from 'url'; +import { EventEmitter } from 'events'; +import { Store } from 'keyv'; +import { Options as CacheSemanticsOptions } from 'http-cache-semantics'; +import ResponseLike = require('responselike'); + +export = CacheableRequest; + +declare const CacheableRequest: CacheableRequest; + +type RequestFn = typeof request; + +interface CacheableRequest { + new (requestFn: RequestFn, storageAdapter?: string | Store): ( + opts: string | URL | (RequestOptions & CacheSemanticsOptions), + cb?: (response: ServerResponse | ResponseLike) => void + ) => CacheableRequest.Emitter; + + RequestError: typeof RequestErrorCls; + CacheError: typeof CacheErrorCls; +} + +declare namespace CacheableRequest { + interface Options { + /** + * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. + * @default true + */ + cache?: boolean; + + /** + * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + * + * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated + * on the next request with `If-None-Match`/`If-Modified-Since` headers. + * @default false + */ + strictTtl?: boolean; + + /** + * Limits TTL. The `number` represents milliseconds. + * @default undefined + */ + maxTtl?: number; + + /** + * When set to `true`, if the DB connection fails we will automatically fallback to a network request. + * DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + * @default false + */ + automaticFailover?: boolean; + + /** + * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a + * new request and override the cache instead. + * @default false + */ + forceRefresh?: boolean; + } + + interface Emitter extends EventEmitter { + addListener(event: 'request', listener: (request: ClientRequest) => void): this; + addListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + on(event: 'request', listener: (request: ClientRequest) => void): this; + on(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + on(event: 'error', listener: (error: RequestError | CacheError) => void): this; + once(event: 'request', listener: (request: ClientRequest) => void): this; + once(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + once(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependOnceListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependOnceListener( + event: 'error', + listener: (error: RequestError | CacheError) => void + ): this; + removeListener(event: 'request', listener: (request: ClientRequest) => void): this; + removeListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + off(event: 'request', listener: (request: ClientRequest) => void): this; + off(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + off(event: 'error', listener: (error: RequestError | CacheError) => void): this; + removeAllListeners(event?: 'request' | 'response' | 'error'): this; + listeners(event: 'request'): Array<(request: ClientRequest) => void>; + listeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + rawListeners(event: 'request'): Array<(request: ClientRequest) => void>; + rawListeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + emit(event: 'request', request: ClientRequest): boolean; + emit(event: 'response', response: ServerResponse | ResponseLike): boolean; + emit(event: 'error', error: RequestError | CacheError): boolean; + eventNames(): Array<'request' | 'response' | 'error'>; + listenerCount(type: 'request' | 'response' | 'error'): number; + } + + type RequestError = RequestErrorCls; + type CacheError = CacheErrorCls; +} + +declare class RequestErrorCls extends Error { + readonly name: 'RequestError'; + + constructor(error: Error); +} +declare class CacheErrorCls extends Error { + readonly name: 'CacheError'; + + constructor(error: Error); +} diff --git a/types/cacheable-request/tsconfig.json b/types/cacheable-request/tsconfig.json new file mode 100644 index 0000000000..635a5b1689 --- /dev/null +++ b/types/cacheable-request/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cacheable-request-tests.ts" + ] +} diff --git a/types/cacheable-request/tslint.json b/types/cacheable-request/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cacheable-request/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 32fbdf6f3f..bd41889e07 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -231,7 +231,7 @@ export interface DecoratedPolicyOptions extends PolicyOptions { /** * @default false */ - getDecoratedValue?: boolean; + getDecoratedValue: boolean | undefined; } export interface GenerateFuncFlags { diff --git a/types/chai-webdriverio/package.json b/types/chai-webdriverio/package.json new file mode 100644 index 0000000000..cd495fe983 --- /dev/null +++ b/types/chai-webdriverio/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/webdriverio": "^4.0.0" + } +} diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ca28a1a9f6..8e795ed77c 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -537,6 +537,7 @@ declare namespace Chart { interface LinearTickOptions extends TickOptions { maxTicksLimit?: number; stepSize?: number; + precision?: number; suggestedMin?: number; suggestedMax?: number; } diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index cb7f884264..863fdb33be 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -485,3 +485,53 @@ new Chartist.Candle('.ct-chart', { } } }); + + +// Create a simple bar chart and line chart with two dimensional arrays +new Chartist.Bar('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) + +new Chartist.Line('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) diff --git a/types/chartist/index.d.ts b/types/chartist/index.d.ts index 9b096839cc..8d700703c9 100644 --- a/types/chartist/index.d.ts +++ b/types/chartist/index.d.ts @@ -93,7 +93,7 @@ declare namespace Chartist { // TODO: come in and tidy this up and make it fit better interface IChartistData { labels?: Array | Array | Array; - series: Array | Array> | Array | Array>; + series: Array | Array> | Array> | Array | Array>; } interface IChartistSeriesData { diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index 7e224ab683..1321d5b83d 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -289,6 +289,17 @@ function test_dom_node() { strong.insertBefore(em); strong.insertBeforeMe(em); element.isReadOnly(); + var prev = node.getPreviousSourceNode(); + prev = node.getPreviousSourceNode(true); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_TEXT); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_COMMENT, node); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_COMMENT, (current: CKEDITOR.dom.node) => false); + var next = node.getNextSourceNode(); + next = node.getNextSourceNode(true); + next = node.getNextSourceNode(true, CKEDITOR.NODE_ELEMENT); + next = node.getNextSourceNode(true, CKEDITOR.NODE_DOCUMENT, node); + next = node.getNextSourceNode(true, CKEDITOR.NODE_DOCUMENT_FRAGMENT, (current: CKEDITOR.dom.node) => true); + console.log(node.type); } function test_dom_nodeList() { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 88646f67d1..910d62f2d7 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -333,6 +333,7 @@ declare namespace CKEDITOR { } class node extends domObject { + type: number; constructor(domNode: Node); appendTo(element: element): element; clone(includeChildren: boolean, cloneId: boolean): node; @@ -347,12 +348,12 @@ declare namespace CKEDITOR { getDocument(): document; getIndex(normalized?: boolean): number; getNext(evaluator?: (node: node) => boolean): node; - getNextSourceNode(startFromSibling: boolean, nodeType: number, guard: node | ((node: node) => boolean)): void; + getNextSourceNode(startFromSibling?: boolean, nodeType?: number, guard?: node | ((node: node) => boolean)): node; getParent(allowFragmentParent?: boolean): element; getParents(closerFirst?: boolean): node[]; getPosition(otherNode: node): void; getPrevious(evaluator?: (node: node) => boolean): node; - getPreviousSourceNode(startFromSibling: boolean, nodeType: number, guard: node | ((node: node) => boolean)): void; + getPreviousSourceNode(startFromSibling?: boolean, nodeType?: number, guard?: node | ((node: node) => boolean)): node; hasAscendant(name: string, includeSelf: boolean): boolean; remove(preserveChildren?: boolean): node; replace(nodeToReplace: node): void; diff --git a/types/clean-css/clean-css-tests.ts b/types/clean-css/clean-css-tests.ts index 9c856d40a1..98049b3ef6 100644 --- a/types/clean-css/clean-css-tests.ts +++ b/types/clean-css/clean-css-tests.ts @@ -81,3 +81,18 @@ new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source, inputSourc console.log(error); } ); + +// test object return when passing options as object +let CleanCssOptions: CleanCSS.Options = { returnPromise: true }; +new CleanCSS(CleanCssOptions).minify(source) + .then((minified: CleanCSS.Output): void => { + console.log(minified.styles); + }).catch((error: any): void => { + console.log(error); + } +); + +CleanCssOptions = { returnPromise: false }; +new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => { + console.log(minified.styles); +}); diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index 244c585e53..9f2dfe9358 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -8,83 +8,78 @@ import { RequestOptions as HttpsRequestOptions } from "https"; import { RequestOptions as HttpRequestOptions } from "http"; -declare namespace CleanCSS { +/** + * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output + */ +interface OptionsBase { /** - * Options passed when initializing a new instance of CleanCSS + * Controls compatibility mode used; defaults to ie10+ using `'*'`. + * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` */ - interface Options { - /** - * Controls compatibility mode used; defaults to ie10+ using `'*'`. - * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` - */ - compatibility?: "*" | "ie9" | "ie8" | "ie7" | CompatibilityOptions; + compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions; - /** - * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function - */ - fetch?: (uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void; + /** + * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function + */ + fetch?: (uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void; - /** - * Controls output CSS formatting; defaults to `false`. - * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. - */ - format?: "beautify" | "keep-breaks" | FormatOptions | false; + /** + * Controls output CSS formatting; defaults to `false`. + * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. + */ + format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false; - /** - * inline option whitelists which @import rules will be processed. Defaults to `'local'` - * Accepts the following values: - * 'local': enables local inlining; - * 'remote': enables remote inlining; - * 'none': disables all inlining; - * 'all': enables all inlining, same as ['local', 'remote']; - * '[uri]': enables remote inlining from the specified uri; - * '![url]': disables remote inlining from the specified uri; - */ - inline?: ReadonlyArray | false; + /** + * inline option whitelists which @import rules will be processed. Defaults to `'local'` + * Accepts the following values: + * 'local': enables local inlining; + * 'remote': enables remote inlining; + * 'none': disables all inlining; + * 'all': enables all inlining, same as ['local', 'remote']; + * '[uri]': enables remote inlining from the specified uri; + * '![url]': disables remote inlining from the specified uri; + */ + inline?: ReadonlyArray | false; - /** - * Controls extra options for inlining remote @import rules - */ - inlineRequest?: HttpRequestOptions | HttpsRequestOptions; + /** + * Controls extra options for inlining remote @import rules + */ + inlineRequest?: HttpRequestOptions | HttpsRequestOptions; - /** - * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; - */ - inlineTimeout?: number; + /** + * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; + */ + inlineTimeout?: number; - /** - * Controls optimization level used; defaults to `1`. - * Level hash exposes `1`, and `2`. - */ - level?: 0 | 1 | 2 | OptimizationsOptions; + /** + * Controls optimization level used; defaults to `1`. + * Level hash exposes `1`, and `2`. + */ + level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions; - /** - * Controls URL rebasing; defaults to `true`; - */ - rebase?: boolean; + /** + * Controls URL rebasing; defaults to `true`; + */ + rebase?: boolean; - /** - * controls a directory to which all URLs are rebased, most likely the directory under which the output file - * will live; defaults to the current directory; - */ - rebaseTo?: string; + /** + * controls a directory to which all URLs are rebased, most likely the directory under which the output file + * will live; defaults to the current directory; + */ + rebaseTo?: string; - /** - * If you prefer clean-css to return a Promise object then you need to explicitely ask for it; defaults to `false` - */ - returnPromise?: boolean; + /** + * Controls whether an output source map is built; defaults to `false` + */ + sourceMap?: boolean; - /** - * Controls whether an output source map is built; defaults to `false` - */ - sourceMap?: boolean; - - /** - * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` - */ - sourceMapInlineSources?: boolean; - } + /** + * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` + */ + sourceMapInlineSources?: boolean; +} +declare namespace CleanCSS { /** * Output returned when calling minify functions */ @@ -650,12 +645,40 @@ declare namespace CleanCSS { minify(sources: Sources, sourceMap?: string): Promise; } + /** + * Options when returning a promise + */ + type OptionsPromise = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise: true + }; + + /** + * Options when returning an output + */ + type OptionsOutput = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise?: false + }; + + /** + * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` + * and want to return a promise, you will need to cast to the correct options type so that TypeScript + * knows what the expected return type will be: + * `(options = options as CleanCSS.OptionsPromise).returnPromise = true` + */ + type Options = OptionsPromise | OptionsOutput; + /** * Constructor interface for CleanCSS */ interface Constructor { - new(options: Options & { returnPromise: true }): MinifierPromise; - new(options?: Options): MinifierOutput; + new(options: OptionsPromise): MinifierPromise; + new(options?: OptionsOutput): MinifierOutput; } } diff --git a/types/cleave.js/cleave.js-tests.tsx b/types/cleave.js/cleave.js-tests.tsx index a826d2607a..461e4f4d05 100644 --- a/types/cleave.js/cleave.js-tests.tsx +++ b/types/cleave.js/cleave.js-tests.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import Cleave = require("cleave.js"); import CleaveReact = require("cleave.js/react"); -import { Props } from "cleave.js/react/props"; +import { Props, ChangeEvent } from "cleave.js/react/props"; const ExampleSelector1 = () => { const cleave = new Cleave("#my-input", { phone: true }); @@ -41,3 +41,17 @@ const ExampleReact2 = (props: Props) => { /> ); }; + +const ExampleReact3 = (props: Props) => { + const handleChange = (e: ChangeEvent) => { + return e.target.rawValue; + }; + return ( + + ); +}; diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 77d2e818ca..11067195ea 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cleave.js 1.3 +// Type definitions for cleave.js 1.4 // Project: https://github.com/nosir/cleave.js // Definitions by: C Lentfort , // J Giancono , diff --git a/types/cleave.js/react/props.d.ts b/types/cleave.js/react/props.d.ts index 6ce47db62c..d881e1b319 100644 --- a/types/cleave.js/react/props.d.ts +++ b/types/cleave.js/react/props.d.ts @@ -3,8 +3,15 @@ import { CleaveOptions } from "../options"; export type InitHandler = (owner: React.ReactInstance) => void; +export interface ChangeEvent extends React.ChangeEvent { + target: { rawValue: string } & EventTarget & T; +} + +export type ChangeEventHandler = React.EventHandler>; + export interface Props extends React.InputHTMLAttributes { onInit?: InitHandler; options: CleaveOptions; htmlRef?: (i: any) => void; + onChange?: ChangeEventHandler; } diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index 7c549761d6..47da5a2140 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -32,9 +32,9 @@ declare namespace Clusterize { } interface Callbacks { - clusterWillChange?(cb: () => void): void; - clusterChanged?(cb: () => void): void; - scrollingProgress?(cb: (progress: number) => void): void; + clusterWillChange?: () => void; + clusterChanged?: () => void; + scrollingProgress?: (progress: number) => void; } } diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts index fb804ac566..65ec9693bd 100644 --- a/types/coinbase/coinbase-tests.ts +++ b/types/coinbase/coinbase-tests.ts @@ -25,7 +25,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined); - account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined); + account.getBuys(null, (error: Error, buy: coinbase.Buy[]): void => undefined); account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined); @@ -33,7 +33,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined); - account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined); + account.getSells(null, (error: Error, deposit: coinbase.Sell[]): void => undefined); account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 6057f58142..82fc32a7d3 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -536,6 +536,21 @@ export class Account implements Resource { */ balance: MoneyHash; + /** + * Allow deposits + */ + allow_deposits: boolean; + + /** + * Allow withdrawls + */ + allow_withdrawals: boolean; + + /** + * Account worth in fiat. + */ + native_balance: MoneyHash; + /** * Promote an account as primary account. * Scope: wallet:accounts:update @@ -630,7 +645,7 @@ export class Account implements Resource { * Lists buys for an account. * Scope: wallet:buys:read */ - getBuys(cb: (error: Error, result: Buy[]) => void): void; + getBuys(opts: null, cb: (error: Error, result: Buy[]) => void): void; /** * Show an individual buy. @@ -663,7 +678,7 @@ export class Account implements Resource { * Lists sells for an account. * Scope: wallet:sells:read */ - getSells(cb: (error: Error, result: Sell[]) => void): void; + getSells(opts: null, cb: (error: Error, result: Sell[]) => void): void; /** * Show an individual sell. @@ -883,7 +898,7 @@ export class Buy implements Resource { /** * Fee associated to this buy */ - fee: MoneyHash; + fees: Fee[]; /** * Has this buy been committed? @@ -900,6 +915,26 @@ export class Buy implements Resource { */ payout_at?: string; + /** + * Unit price of the base currency. + */ + unit_price: UnitPrice; + + /** + * Hold period for transfer. + */ + hold_business_days: number; + + /** + * Is it the first buy for this symbol? + */ + is_first_buy: boolean; + + /** + * Is there another action required to make the transfer pass? + */ + requires_completion_step: boolean; + /** * Completes a buy that is created in commit: false state. * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you @@ -910,6 +945,32 @@ export class Buy implements Resource { commit(cb: (error: Error, transaction: Buy) => void): void; } +export interface Fee { + /** + * Amount associated to this fee + */ + amount: MoneyHash; + /** + * Fee beneficiary ("bank", "coinbase", ...) + */ + type: string; +} + +export interface UnitPrice { + /** + * Amount as floating-point in a string + */ + amount: string; + /** + * Currency e.g. "BTC" (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Type of price + */ + scale: number; +} + export type SellStatus = "created" | "completed" | "canceled"; /** diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index 96bb2774c5..2f2899b44a 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -4,15 +4,18 @@ // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export type NodeType = + 'text' |'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | + 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + export class Node { - constructor(nodeType: string, sourcepos?: Position); + constructor(nodeType: NodeType, sourcepos?: Position); /** * (read-only): a String, one of text, softbreak, linebreak, emph, strong, html_inline, link, image, code, document, paragraph, * block_quote, item, list, heading, code_block, html_block, thematic_break. */ - readonly type: 'text' | 'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | - 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + readonly type: NodeType; /** * (read-only): a Node or null. */ diff --git a/types/content-range/content-range-tests.ts b/types/content-range/content-range-tests.ts new file mode 100644 index 0000000000..c482d6f072 --- /dev/null +++ b/types/content-range/content-range-tests.ts @@ -0,0 +1,23 @@ +import { format, parse } from 'content-range'; + +format({ + first: 10, + last: 100, + length: 100, + limit: 20, + unit: 'items', +}); + +format({ + length: null, + unit: 'bytes', +}); + +const parts = parse('items 10-29/100'); + +if (parts) { + parts.first; + parts.last; + parts.length; + parts.unit; +} diff --git a/types/content-range/index.d.ts b/types/content-range/index.d.ts new file mode 100644 index 0000000000..b8ee780541 --- /dev/null +++ b/types/content-range/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for content-range 1.1 +// Project: https://github.com/neoziro/content-range +// Definitions by: Alex Brick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ContentRangeFormatOptions { + first?: number; + last?: number; + length: number | null; + limit?: number; + unit: string; +} + +export interface ContentRangeParts { + first: number | null; + last: number | null; + length: number | null; + unit: string; +} + +export function format(options: ContentRangeFormatOptions): string; +export function parse(str: string): ContentRangeParts | null; diff --git a/types/content-range/tsconfig.json b/types/content-range/tsconfig.json new file mode 100644 index 0000000000..a2649416e0 --- /dev/null +++ b/types/content-range/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "content-range-tests.ts" + ] +} diff --git a/types/content-range/tslint.json b/types/content-range/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/content-range/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index b27bfdf90c..596a9536ca 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.3 +// Type definitions for cron 1.6 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Lundarl Gholoi @@ -9,8 +9,9 @@ export declare class CronTime { * Create a new ```CronTime```. * @param source The time to fire off your job. This can be in the form of cron syntax or a JS ```Date``` object. * @param zone Timezone name. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * @param utcOffset UTC offset. Don't use both ```zone``` and ```utcOffset``` together or weird things may happen. */ - constructor(source: string | Date, zone?: string); + constructor(source: string | Date, zone?: string, utcOffset?: string | number); /** * Tells you when ```CronTime``` will be run. @@ -29,19 +30,19 @@ export declare interface CronJobParameters { */ cronTime: string | Date; /** - * The function to fire at the specified time. + * The function to fire at the specified time. If an ```onComplete``` callback was provided, ```onTick``` will receive it as an argument. ```onTick``` may call ```onComplete``` when it has finished its work. */ onTick: () => void; /** - * A function that will fire when the job is complete, when it is stopped. + * A function that will fire when the job is stopped with ```job.stop()```, and may also be called by ```onTick``` at the end of each run. */ onComplete?: () => void; /** - * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your onTick function, it just gives you more control over the behavior of your jobs. + * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your ```onTick``` function, it just gives you more control over the behavior of your jobs. */ start?: boolean; /** - * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. */ timeZone?: string; /** @@ -52,6 +53,14 @@ export declare interface CronJobParameters { * This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. */ runOnInit?: boolean; + /** + * This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + */ + utcOffset?: string | number; + /** + * If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. + */ + unrefTimeout?: boolean; } export declare class CronJob { @@ -73,8 +82,10 @@ export declare class CronJob { * @param timeZone Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). * @param context The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call ```this.stop()```. However, if you change this you'll have access to the functions and values within your context object. * @param runOnInit This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. + * @param utcOffset This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + * @param unrefTimeout If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. */ - constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean); + constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); /** * Create a new ```CronJob```. * @param options Job parameters. @@ -111,7 +122,7 @@ export declare class CronJob { } export declare var job: - ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean) => CronJob) + ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) | ((options: CronJobParameters) => CronJob); export declare var time: (source: string | Date, zone?: string) => CronTime; export declare var sendAt: (cronTime: CronTime) => Date; diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 8f54ee4f5c..3b773e95b1 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -10,17 +10,20 @@ CustomFunctions.associate({ RANDOM: (n: number) => n * Math.random() }); +function callerAddress(invocation: CustomFunctions.Invocation) { + return invocation.address; +} + async function getStockValues(ticker: string): Promise { const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())["price"]; } -async function getStockValuesCancellable( - ticker: string, - handler: CustomFunctions.CancelableHandler -): Promise { +async function getStockValuesCancellable(ticker: string, + invocation: CustomFunctions.CancelableInvocation): Promise { + const address = invocation.address; let shouldStop = false; - handler.onCanceled = () => (shouldStop = true); + invocation.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { @@ -31,10 +34,9 @@ async function getStockValuesCancellable( return (await response.json())["price"]; } -function stockPriceStream( - ticker: string, - handler: CustomFunctions.StreamingHandler -) { +function stockPriceStream(ticker: string, + invocation: CustomFunctions.StreamingInvocation) { + const address = invocation.address; const updateFrequency = 10 /* milliseconds*/; let isPending = false; @@ -49,14 +51,14 @@ function stockPriceStream( try { const response = await fetch(url); const data = await response.json(); - handler.setResult(data.price); + invocation.setResult(data.price); } catch (error) { - handler.setResult(error); + invocation.setResult(error); } isPending = false; }, updateFrequency); - handler.onCanceled = () => { + invocation.onCanceled = () => { clearInterval(timer); }; } diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index 174308c131..c907fe327e 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Custom Functions 1.4 // Project: https://github.com/OfficeDev/office-js -// Definitions by: OfficeDev , Michael Zlatkovsky , Michelle Scharlock +// Definitions by: OfficeDev , +// Adam Krantz , +// Michael Zlatkovsky , +// Michelle Scharlock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -10,8 +13,8 @@ Copyright (c) Microsoft Corporation */ /** - * CustomFunctions namespace, used by Excel Custom Functions * @beta + * CustomFunctions namespace, used by Excel Custom Functions */ declare namespace CustomFunctions { /** @@ -26,30 +29,67 @@ declare namespace CustomFunctions { function associate(mappings: { [key: string]: Function }): void; /** - * A handler passed automatically as the last parameter - * to a streaming function. With this parameter, a - * function can use handler.setResult to set a cell value - * or hook into the handler.onCanceled event to - * to handle what happens when the function stops streaming. * @beta + * Provides information about the invocation of a custom function. */ - interface StreamingHandler extends CancelableHandler { + interface Invocation { /** - * Sets the returned result for a streaming custom function. * @beta + * The cell address where the function is being called, if requested, otherwise undefined. + * + * To request the address for the function, in the metadata JSON file, the function options should specify: + * `{ "requiresAddress": true }` + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@requiresAddress`. */ - setResult: (value: T | Error) => void; + address?: string; } /** * @beta - * CancelableHandler interface + * Provides information about the invocation of a cancelable custom function. + * A cancelable custom function can provide a handler for the onCanceled event. + * + * To indicate that a function is cancelable, in the metadata JSON file, the function options should specify: + * `{ "cancelable": true }` + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@cancelable`. */ - interface CancelableHandler { + interface CancelableInvocation extends Invocation { /** - * Handles what should occur when a custom function is canceled. * @beta + * Event handler called when the custom function is canceled. */ onCanceled: () => void; } + + /** + * @beta + * @deprecated Use `CancelableInvocation` instead. + */ + interface CancelableHandler extends CancelableInvocation { + } + + /** + * @beta + * Provides information about the invocation of a streaming custom function. + * A streaming custom function can provide results which can change over time. + * + * Call `setResult()` one or more times to provide the result instead of returning + * a result from the function. + */ + interface StreamingInvocation extends CancelableInvocation { + /** + * @beta + * Set the result for the custom function. May be called more than once. + */ + setResult: (value: ResultType | Error) => void; + } + + /** + * @beta + * @deprecated Use `StreamingInvocation` instead. + */ + interface StreamingHandler extends StreamingInvocation { + } } diff --git a/types/custom-functions-runtime/tslint.json b/types/custom-functions-runtime/tslint.json index ad17c76132..bb858f4682 100644 --- a/types/custom-functions-runtime/tslint.json +++ b/types/custom-functions-runtime/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "file-name-casing": false + "file-name-casing": false, + "no-empty-interface": false } } diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 391e2786be..11b9e0de35 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -181,7 +181,7 @@ export function ascending(a: Primitive | undefined, b: Primitive | undefined): n // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** - * Compares two primitive values for sorting (in ascending order). + * Compares two primitive values for sorting (in descending order). */ export function descending(a: Primitive | undefined, b: Primitive | undefined): number; diff --git a/types/defaults-deep/defaults-deep-tests.ts b/types/defaults-deep/defaults-deep-tests.ts new file mode 100644 index 0000000000..daabc46d7d --- /dev/null +++ b/types/defaults-deep/defaults-deep-tests.ts @@ -0,0 +1,7 @@ +import defaults = require('defaults-deep'); + +defaults(); +defaults({a: 'foo'}); +defaults({a: 'foo'}, {a: 'bar'}); +defaults({a: 'foo'}, {a: 'bar'}, {a: 'foobar'}); +defaults({a: {b: 'foo'}}, {a: {b: 'bar'}}); diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts new file mode 100644 index 0000000000..749257eb88 --- /dev/null +++ b/types/defaults-deep/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for defaults-deep 0.2 +// Project: https://github.com/jonschlinkert/defaults-deep +// Definitions by: Hugo Alliaume +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Obj { + [k: string]: any; +} + +declare function defaultsDeep(...objs: Obj[]): Obj; + +export = defaultsDeep; diff --git a/types/defaults-deep/tsconfig.json b/types/defaults-deep/tsconfig.json new file mode 100644 index 0000000000..9b7c12bf2b --- /dev/null +++ b/types/defaults-deep/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", + "defaults-deep-tests.ts" + ] +} diff --git a/types/defaults-deep/tslint.json b/types/defaults-deep/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defaults-deep/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index f2e322b0e3..5502cdcaf2 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1455,13 +1455,13 @@ interface GanttStatic { * exports a Gantt chart into the PDF format * @param _export_ an object with export settings (see the details) */ - exportToPDF(_export_: any): void; + exportToPDF(_export_?: any): void; /** * exports a Gantt chart into the PNG format * @param _export_ an object with export settings (see the details) */ - exportToPNG(_export_: any): void; + exportToPNG(_export_?: any): void; /** * returns all dependency loops in the chart @@ -2242,4 +2242,4 @@ declare module "gantt" { declare module "Gantt" { export = Gantt; -} \ No newline at end of file +} diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 2f640da490..845b307132 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -1,47 +1,55 @@ -import jsdiff = require('diff'); +import * as diff from 'diff'; + const one = 'beep boop'; const other = 'beep boob blah'; -let diff = jsdiff.diffChars(one, other); -printDiff(diff); +let changes = diff.diffChars(one, other); +examineChanges(changes); -const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +// $ExpectType void +diff.diffChars(one, other, { + callback: (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined + }, +}); +// $ExpectType void +diff.diffChars(one, other, (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined +}); + +const diffArraysResult = diff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); diffArraysResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType string[] + result.count; // $ExpectType number | undefined }); interface DiffObj { value: number; } -const a: DiffObj = {value: 0}; -const b: DiffObj = {value: 1}; -const c: DiffObj = {value: 2}; -const d: DiffObj = {value: 3}; -const arrayOptions: jsdiff.IArrayOptions = { - comparator: (left: DiffObj, right: DiffObj) => { - return left.value === right.value; - } +const a: DiffObj = { value: 0 }; +const b: DiffObj = { value: 1 }; +const c: DiffObj = { value: 2 }; +const d: DiffObj = { value: 3 }; +const arrayOptions: diff.ArrayOptions = { + comparator: (left, right) => { + return left.value === right.value; + }, }; -const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); -diffResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } +const arrayChanges = diff.diffArrays([a, b, c], [a, b, d], arrayOptions); +arrayChanges.forEach(result => { + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType DiffObj[] + result.count; // $ExpectType number | undefined }); // -------------------------- -class LineDiffWithoutWhitespace extends jsdiff.Diff { +class LineDiffWithoutWhitespace extends diff.Diff { tokenize(value: string): any { return value.split(/^/m); } @@ -52,71 +60,62 @@ class LineDiffWithoutWhitespace extends jsdiff.Diff { } const obj = new LineDiffWithoutWhitespace(); -diff = obj.diff(one, other); -printDiff(diff); +changes = obj.diff(one, other); +examineChanges(changes); -function printDiff(diff: jsdiff.IDiffResult[]) { - function addLineHeader(decorator: string, str: string | string[]) { - return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { - if (index === array.length - 1 && line === "") { - return line; - } else { - return decorator + line; - } - }).join("\n"); - } - - diff.forEach((part) => { - if (part.added) { - console.log(addLineHeader("+", part.value)); - } else if (part.removed) { - console.log(addLineHeader("-", part.value)); - } else { - console.log(addLineHeader(" ", part.value)); - } +function examineChanges(diff: diff.Change[]) { + diff.forEach(part => { + part.added; // $ExpectType boolean | undefined + part.removed; // $ExpectType boolean | undefined + part.value; // $ExpectType string + part.count; // $ExpectType number | undefined }); } -function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyPatch = jsdiff.parsePatch( - jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, - "old", "new", { context: 1 })); +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyPatch = diff.parsePatch( + diff.createTwoFilesPatch('oldFile.ts', 'newFile.ts', oldStr, newStr, 'old', 'new', { + context: 1, + }) + ); - if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { - console.error("Patch did not match uniDiff"); + if ( + JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== + JSON.stringify(uniDiff, Object.keys(uniDiff).sort()) + ) { + throw new Error('Patch did not match uniDiff'); } } -function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyApply = [ - jsdiff.applyPatch(oldStr, uniDiff), - jsdiff.applyPatch(oldStr, [uniDiff]) - ]; - jsdiff.applyPatches([uniDiff], { - loadFile: (index: number, callback: (err: Error, data: string) => void) => { +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])]; + diff.applyPatches([uniDiff], { + loadFile: (index, callback) => { + index; // $ExpectType ParsedDiff callback(undefined, one); }, - patched: (index: number, content: string) => { + patched: (index, content) => { + index; // $ExpectType ParsedDiff verifyApply.push(content); }, complete: (err?: Error) => { if (err) { - console.error(err); + throw err; } verifyApply.forEach(result => { if (result !== newStr) { - console.error("Result did not match newStr"); + throw new Error('Result did not match newStr'); } }); - } + }, }); } -const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, - "old", "new", { context: 1 }); +const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', { + context: 1, +}); verifyPatchMethods(one, other, uniDiffPatch); -const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", - { context: 1 }); -const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; +const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 }); +const uniDiffApply = diff.parsePatch(uniDiffStr)[0]; verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 760aee4e61..fa0e4e2e3d 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -1,121 +1,402 @@ -// Type definitions for diff 3.5 +// Type definitions for diff 4.0 // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // szdc // moc-yuto +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export = JsDiff; -export as namespace JsDiff; +export as namespace Diff; -declare namespace JsDiff { - interface IOptions { - ignoreCase: boolean; - } +export type Callback = (err: undefined, value?: Change[]) => void; - interface ILinesOptions extends IOptions { - ignoreWhitespace?: boolean; - newlineIsToken?: boolean; - } - - interface IArrayOptions { - comparator?: (left: any, right: any) => boolean; - } - - interface IDiffResult { - value: string; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IDiffArraysResult { - value: T[]; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IBestPath { - newPos: number; - componenets: IDiffResult[]; - } - - interface IHunk { - oldStart: number; - oldLines: number; - newStart: number; - newLines: number; - lines: string[]; - } - - interface IUniDiff { - oldFileName: string; - newFileName: string; - oldHeader: string; - newHeader: string; - index: string; - hunks: IHunk[]; - } - - class Diff { - diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; - - pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; - - extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; - - equals(left: string, right: string): boolean; - - removeEmpty(array: any[]): any[]; - - castInput(value: any): any; - - join(chars: string[]): string; - - tokenize(value: string): any; // return types are string or string[] - } - - function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; - - function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; - - function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; - - function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; - - function applyPatches(uniDiff: IUniDiff[], options: { - loadFile(index: number, callback: (err: Error, data: string) => void): void, - patched(index: number, content: string): void, - complete(err?: Error): void - }): void; - - function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; - - function convertChangesToXML(changes: IDiffResult[]): string; - - function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; - - function merge(mine: string, theirs: string, base: string): IUniDiff; - - function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +export interface CallbackOptions { + /** + * Callback to call with the result instead of returning the result directly. + */ + callback: Callback; } + +export interface BaseOptions { + /** + * `true` to ignore casing difference. + * @default false + */ + ignoreCase?: boolean; +} + +export interface WordsOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`. + */ + ignoreWhitespace?: boolean; +} + +export interface LinesOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`. + */ + ignoreWhitespace?: boolean; + + /** + * `true` to treat newline characters as separate tokens. This allows for changes to the newline structure + * to occur independently of the line content and to be treated as such. In general this is the more + * human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer + * friendly output. + */ + newlineIsToken?: boolean; +} + +export interface JsonOptions extends LinesOptions { + /** + * Replacer used to stringify the properties of the passed objects. + */ + stringifyReplacer?: (key: string, value: any) => any; + + /** + * The value to use when `undefined` values in the passed objects are encountered during stringification. + * Will only be used if `stringifyReplacer` option wasn't specified. + * @default undefined + */ + undefinedReplacement?: any; +} + +export interface ArrayOptions extends BaseOptions { + /** + * Comparator for custom equality checks. + */ + comparator?: (left: TLeft, right: TRight) => boolean; +} + +export interface PatchOptions extends LinesOptions { + /** + * Describes how many lines of context should be included. + * @default 4 + */ + context?: number; +} + +export interface ApplyPatchOptions { + /** + * Number of lines that are allowed to differ before rejecting a patch. + * @default 0 + */ + fuzzFactor?: number; + + /** + * Callback used to compare to given lines to determine if they should be considered equal when patching. + * Should return `false` if the lines should be rejected. + * + * @default strict equality + */ + compareLine?: ( + lineNumber: number, + line: string, + operation: '-' | ' ', + patchContent: string + ) => boolean; +} + +export interface ApplyPatchesOptions { + loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; + patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; + complete(err: any): void; +} + +export interface Change { + count?: number; + /** + * Text content. + */ + value: string; + /** + * `true` if the value was inserted into the new string. + */ + added?: boolean; + /** + * `true` if the value was removed from the old string. + */ + removed?: boolean; +} + +export interface ArrayChange { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; +} + +export interface ParsedDiff { + index?: string; + oldFileName?: string; + newFileName?: string; + oldHeader?: string; + newHeader?: string; + hunks: Hunk[]; +} + +export interface Hunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; +} + +export interface BestPath { + newPos: number; + componenets: Change[]; +} + +export class Diff { + diff( + oldString: string, + newString: string, + options?: Callback | (ArrayOptions & Partial) + ): Change[]; + + pushComponent(components: Change[], added: boolean, removed: boolean): void; + + extractCommon( + basePath: BestPath, + newString: string, + oldString: string, + diagonalPath: number + ): number; + + equals(left: any, right: any): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] +} + +/** + * Diffs two blocks of text, comparing character by character. + * + * @returns A list of change objects. + */ +export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffChars( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, ignoring whitespace. + * + * @returns A list of change objects. + */ +export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[]; +export function diffWords( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, treating whitespace as significant. + * + * @returns A list of change objects. + */ +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options?: WordsOptions +): Change[]; +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line. + * + * @returns A list of change objects. + */ +export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. + * + * @returns A list of change objects. + */ +export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffTrimmedLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing sentence by sentence. + * + * @returns A list of change objects. + */ +export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffSentences( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing CSS tokens. + * + * @returns A list of change objects. + */ +export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffCss( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter + * in this comparison. + * + * @returns A list of change objects. + */ +export function diffJson( + oldObj: string | object, + newObj: string | object, + options?: JsonOptions +): Change[]; +export function diffJson( + oldObj: string | object, + newObj: string | object, + options: Callback | (JsonOptions & CallbackOptions) +): void; + +/** + * Diffs two arrays, comparing each item for strict equality (`===`). + * + * @returns A list of change objects. + */ +export function diffArrays( + oldArr: TOld[], + newArr: TNew[], + options?: ArrayOptions +): Array>; + +/** + * Creates a unified diff patch. + * + * @param oldFileName String to be output in the filename section of the patch for the removals. + * @param newFileName String to be output in the filename section of the patch for the additions. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createTwoFilesPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * Creates a unified diff patch. + * Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`. + * + * @param fileName String to be output in the filename section. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createPatch( + fileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing. + * Parameters are the same as `createTwoFilesPatch()`. + * + * @param oldFileName String to be output in the `oldFileName` hunk property. + * @param newFileName String to be output in the `newFileName` hunk property. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the `oldHeader` hunk property. + * @param newHeader Additional information to include in the `newHeader` hunk property. + * @returns An object with an array of hunk objects. + */ +export function structuredPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): ParsedDiff; + +/** + * Applies a unified diff patch. + * + * @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods. + * @returns A string containing new version of provided data. + */ +export function applyPatch( + source: string, + patch: string | ParsedDiff | [ParsedDiff], + options?: ApplyPatchOptions +): string; + +/** + * Applies one or more patches. + * This method will iterate over the contents of the patch and apply to data provided through callbacks. + * + * The general flow for each patch index is: + * + * 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file + * and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be + * the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback. + * Passing an `err` will terminate further patch execution. + * 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void; + +/** + * Parses a patch into structured data. + * + * @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method. + */ +export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[]; + +/** + * Converts a list of changes to a serialized XML format. + */ +export function convertChangesToXML(changes: Change[]): string; + +/** + * Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format. + */ +export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>; + +export function merge(mine: string, theirs: string, base: string): ParsedDiff; + +export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; diff --git a/types/diff/tsconfig.json b/types/diff/tsconfig.json index 9a1fdba840..b32089d091 100644 --- a/types/diff/tsconfig.json +++ b/types/diff/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +20,4 @@ "index.d.ts", "diff-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/diff/tslint.json b/types/diff/tslint.json index 1b7b2672e6..3db14f85ea 100644 --- a/types/diff/tslint.json +++ b/types/diff/tslint.json @@ -1,7 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "interface-name": false, - "export-just-namespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/diff/v3/diff-tests.ts b/types/diff/v3/diff-tests.ts new file mode 100644 index 0000000000..2f640da490 --- /dev/null +++ b/types/diff/v3/diff-tests.ts @@ -0,0 +1,122 @@ +import jsdiff = require('diff'); +const one = 'beep boop'; +const other = 'beep boob blah'; + +let diff = jsdiff.diffChars(one, other); +printDiff(diff); + +const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +diffArraysResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +interface DiffObj { + value: number; +} +const a: DiffObj = {value: 0}; +const b: DiffObj = {value: 1}; +const c: DiffObj = {value: 2}; +const d: DiffObj = {value: 3}; +const arrayOptions: jsdiff.IArrayOptions = { + comparator: (left: DiffObj, right: DiffObj) => { + return left.value === right.value; + } +}; +const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); +diffResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +// -------------------------- + +class LineDiffWithoutWhitespace extends jsdiff.Diff { + tokenize(value: string): any { + return value.split(/^/m); + } + + equals(left: string, right: string): boolean { + return left.trim() === right.trim(); + } +} + +const obj = new LineDiffWithoutWhitespace(); +diff = obj.diff(one, other); +printDiff(diff); + +function printDiff(diff: jsdiff.IDiffResult[]) { + function addLineHeader(decorator: string, str: string | string[]) { + return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { + if (index === array.length - 1 && line === "") { + return line; + } else { + return decorator + line; + } + }).join("\n"); + } + + diff.forEach((part) => { + if (part.added) { + console.log(addLineHeader("+", part.value)); + } else if (part.removed) { + console.log(addLineHeader("-", part.value)); + } else { + console.log(addLineHeader(" ", part.value)); + } + }); +} + +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyPatch = jsdiff.parsePatch( + jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, + "old", "new", { context: 1 })); + + if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { + console.error("Patch did not match uniDiff"); + } +} +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyApply = [ + jsdiff.applyPatch(oldStr, uniDiff), + jsdiff.applyPatch(oldStr, [uniDiff]) + ]; + jsdiff.applyPatches([uniDiff], { + loadFile: (index: number, callback: (err: Error, data: string) => void) => { + callback(undefined, one); + }, + patched: (index: number, content: string) => { + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + console.error(err); + } + + verifyApply.forEach(result => { + if (result !== newStr) { + console.error("Result did not match newStr"); + } + }); + } + }); +} + +const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, + "old", "new", { context: 1 }); +verifyPatchMethods(one, other, uniDiffPatch); + +const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", + { context: 1 }); +const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; +verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/v3/index.d.ts b/types/diff/v3/index.d.ts new file mode 100644 index 0000000000..760aee4e61 --- /dev/null +++ b/types/diff/v3/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for diff 3.5 +// Project: https://github.com/kpdecker/jsdiff +// Definitions by: vvakame +// szdc +// moc-yuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = JsDiff; +export as namespace JsDiff; + +declare namespace JsDiff { + interface IOptions { + ignoreCase: boolean; + } + + interface ILinesOptions extends IOptions { + ignoreWhitespace?: boolean; + newlineIsToken?: boolean; + } + + interface IArrayOptions { + comparator?: (left: any, right: any) => boolean; + } + + interface IDiffResult { + value: string; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IDiffArraysResult { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IBestPath { + newPos: number; + componenets: IDiffResult[]; + } + + interface IHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; + } + + interface IUniDiff { + oldFileName: string; + newFileName: string; + oldHeader: string; + newHeader: string; + index: string; + hunks: IHunk[]; + } + + class Diff { + diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; + + pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; + + extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; + + equals(left: string, right: string): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] + } + + function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; + + function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; + + function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; + + function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; + + function applyPatches(uniDiff: IUniDiff[], options: { + loadFile(index: number, callback: (err: Error, data: string) => void): void, + patched(index: number, content: string): void, + complete(err?: Error): void + }): void; + + function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; + + function convertChangesToXML(changes: IDiffResult[]): string; + + function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; + + function merge(mine: string, theirs: string, base: string): IUniDiff; + + function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +} diff --git a/types/diff/v3/tsconfig.json b/types/diff/v3/tsconfig.json new file mode 100644 index 0000000000..92e1861ec8 --- /dev/null +++ b/types/diff/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "diff": [ + "diff/v3" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "diff-tests.ts" + ] +} diff --git a/types/diff/v3/tslint.json b/types/diff/v3/tslint.json new file mode 100644 index 0000000000..1b7b2672e6 --- /dev/null +++ b/types/diff/v3/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-name": false, + "export-just-namespace": false + } +} diff --git a/types/dlv/dlv-tests.ts b/types/dlv/dlv-tests.ts new file mode 100644 index 0000000000..abe4b259c3 --- /dev/null +++ b/types/dlv/dlv-tests.ts @@ -0,0 +1,44 @@ +import dlv from 'dlv'; + +const obj = { + undef: undefined, + zero: 0, + one: 1, + n: null, + f: false, + a: { + two: 2, + b: { + three: 3, + c: { + four: 4 + } + } + } +}; + +// Test without defaults +dlv(obj, ''); +dlv(obj, 'one'); +dlv(obj, 'one.two'); +dlv(obj, 'a'); +dlv(obj, 'a.two'); +dlv(obj, 'a.b'); +dlv(obj, 'a.b.three'); +dlv(obj, 'a.b.c'); +dlv(obj, 'a.b.c.four'); +dlv(obj, 'n'); +dlv(obj, 'n.badkey'); +dlv(obj, 'f'); +dlv(obj, 'f.badkey'); + +// Test defaults +dlv(obj, '', 'foo'); +dlv(obj, 'undef', 'foo'); +dlv(obj, 'n', null); +dlv(obj, 'n.badkey', 'foo'); +dlv(obj, 'zero', 0); +dlv(obj, 'a.badkey', 'foo'); +dlv(obj, 'a.badkey.anotherbadkey', 'foo'); +dlv(obj, 'f', false); +dlv(obj, 'f.badkey', 'foo'); diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts new file mode 100644 index 0000000000..5813ec0595 --- /dev/null +++ b/types/dlv/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for dlv 1.1 +// Project: https://github.com/developit/dlv#readme +// Definitions by: Ryan Sonshine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Safely get a dot-notated path within a nested object, with ability to + * return a default if the full key path does not exist or the value is + * undefined + */ +export default function dlv(object: object, key: string | string[], defaultValue?: any): any; diff --git a/types/dlv/tsconfig.json b/types/dlv/tsconfig.json new file mode 100644 index 0000000000..222ce070e7 --- /dev/null +++ b/types/dlv/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "dlv-tests.ts" + ] +} diff --git a/types/dlv/tslint.json b/types/dlv/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dlv/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ember__string/ember__string-tests.ts b/types/ember__string/ember__string-tests.ts index 1f045b849d..500c67546e 100644 --- a/types/ember__string/ember__string-tests.ts +++ b/types/ember__string/ember__string-tests.ts @@ -1,4 +1,4 @@ -import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } from '@ember/string'; +import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w, isHTMLSafe } from '@ember/string'; import { SafeString } from 'handlebars'; dasherize(); // $ExpectError @@ -36,3 +36,11 @@ loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string const handlebarsSafeString: SafeString = htmlSafe('lorem ipsum...'); htmlSafe('lorem ipsum...'); // $ExpectType SafeString const regularString: string = htmlSafe('lorem ipsum...'); // $ExpectError + +function isSafeTest(a: string|Handlebars.SafeString) { + if (isHTMLSafe(a)) { + a = a.toString(); + } + + camelize(a); +} diff --git a/types/ember__string/index.d.ts b/types/ember__string/index.d.ts index 8a2a46c022..66b5199bfd 100644 --- a/types/ember__string/index.d.ts +++ b/types/ember__string/index.d.ts @@ -11,8 +11,8 @@ export function capitalize(str: string): string; export function classify(str: string): string; export function dasherize(str: string): string; export function decamelize(str: string): string; -export function htmlSafe(str: string): Handlebars.SafeString; -export function isHTMLSafe(str: string): boolean; +export function htmlSafe(str: string): SafeString; +export function isHTMLSafe(str: any): str is SafeString; export function loc(template: string, args?: string[]): string; export function underscore(str: string): string; export function w(str: string): string[]; diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts index a92bcb77ff..8ea741ca9f 100644 --- a/types/emoji-mart/index.d.ts +++ b/types/emoji-mart/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Nick Winans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 0711243d0c..0c7e2c2e90 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -35,6 +35,10 @@ interface MyComponentState { stateProperty: string; } +function toComponentType(Component: ComponentClass | StatelessComponent): ComponentClass | StatelessComponent { + return Component; +} + class MyComponent extends Component { handleEcho(value: string) { return value; @@ -59,6 +63,8 @@ const MyStatelessComponent = (props: StatelessProps) => ; const AnotherStatelessComponent = (props: AnotherStatelessProps) => ; +const ComponentType = toComponentType(MyComponent); + // Enzyme.configure function configureTest() { const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; @@ -859,6 +865,14 @@ function ReactWrapperTest() { reactWrapper = new ReactWrapper(, undefined, { attachTo: document.createElement('div') }); reactWrapper = new ReactWrapper(, reactWrapper, { attachTo: document.createElement('div') }); } + + function test_component_type() { + const wrapper1 = shallow(
); + wrapper1.find(ComponentType).props().stringProp; // $ExpectType string + + const wrapper2 = mount(
); + wrapper2.find(ComponentType).props().stringProp; // $ExpectType string + } } // CheerioWrapper diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 0818b4e5ce..58e5938a8f 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -27,7 +27,9 @@ export interface ComponentClass { new(props: Props, context?: any): Component; } -export type StatelessComponent = (props: Props, context?: any) => JSX.Element; +export type StatelessComponent = (props: Props, context?: any) => JSX.Element | null; + +export type ComponentType = ComponentClass | StatelessComponent; /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the @@ -372,8 +374,8 @@ export class ShallowWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ShallowWrapper; find(statelessComponent: StatelessComponent): ShallowWrapper; + find(component: ComponentType): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -381,8 +383,8 @@ export class ShallowWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(component: ComponentType): ShallowWrapper; filter(props: EnzymePropSelector | string): ShallowWrapper; /** @@ -394,8 +396,8 @@ export class ShallowWrapper

{ * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; + children(component: ComponentType): ShallowWrapper; children(selector: string): ShallowWrapper; children(props?: EnzymePropSelector): ShallowWrapper; @@ -425,8 +427,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(component: ComponentType): ShallowWrapper; parents(selector: string): ShallowWrapper; parents(props?: EnzymePropSelector): ShallowWrapper; @@ -436,8 +438,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(component: ComponentType): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -487,8 +489,8 @@ export class ReactWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ReactWrapper; find(statelessComponent: StatelessComponent): ReactWrapper; + find(component: ComponentType): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -501,16 +503,16 @@ export class ReactWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ReactWrapper; filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(component: ComponentType): ReactWrapper; filter(props: EnzymePropSelector | string): ReactWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ReactWrapper; children(statelessComponent: StatelessComponent): ReactWrapper; + children(component: ComponentType): ReactWrapper; children(selector: string): ReactWrapper; children(props?: EnzymePropSelector): ReactWrapper; @@ -526,8 +528,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ReactWrapper; parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(component: ComponentType): ReactWrapper; parents(selector: string): ReactWrapper; parents(props?: EnzymePropSelector): ReactWrapper; @@ -537,8 +539,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ReactWrapper; closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(component: ComponentType): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index ed211d220e..6d175716b3 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -539,4 +539,12 @@ ruleTester.run('my-rule', rule, { ] }); +ruleTester.run('simple-valid-test', rule, { + valid: [ + 'foo', + 'bar', + { code: 'foo', options: [{ allowFoo: true }] }, + ] +}); + //#endregion diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 01f39ee83e..f1a585046c 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -540,7 +540,7 @@ export class RuleTester { name: string, rule: Rule.RuleModule, tests: { - valid?: RuleTester.ValidTestCase[]; + valid?: Array; invalid?: RuleTester.InvalidTestCase[]; }, ): void; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 1b24c3151c..c206bc12ff 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -2451,6 +2451,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v24/index.d.ts b/types/expo/v24/index.d.ts index 35d1e9be92..7c515a0268 100644 --- a/types/expo/v24/index.d.ts +++ b/types/expo/v24/index.d.ts @@ -1949,6 +1949,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v25/index.d.ts b/types/expo/v25/index.d.ts index 766c055911..9e2da6c790 100644 --- a/types/expo/v25/index.d.ts +++ b/types/expo/v25/index.d.ts @@ -1978,6 +1978,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 9804579e66..e8386db63c 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -2006,6 +2006,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v27/index.d.ts b/types/expo/v27/index.d.ts index a80fb657ee..179315ba69 100644 --- a/types/expo/v27/index.d.ts +++ b/types/expo/v27/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v30/index.d.ts b/types/expo/v30/index.d.ts index d5891bad2d..8a77777c49 100644 --- a/types/expo/v30/index.d.ts +++ b/types/expo/v30/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo__vector-icons/expo__vector-icons-tests.tsx b/types/expo__vector-icons/expo__vector-icons-tests.tsx index 7d918c917f..33e1056957 100644 --- a/types/expo__vector-icons/expo__vector-icons-tests.tsx +++ b/types/expo__vector-icons/expo__vector-icons-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { View, Text, TabBarIOS } from 'react-native'; -import { createIconSet, MaterialIcons, FontAwesome, Ionicons } from 'expo__vector-icons'; +import { createIconSet, MaterialIcons, FontAwesome, AntDesign } from 'expo__vector-icons'; const glyphMap = { custom: 58918 @@ -48,7 +48,7 @@ class TabTest extends React.Component<{}, { selectedTab: string }> { render() { return ( - { onPress={() => this.setState({ selectedTab: 'tab1' })} > - + - { onPress={() => this.setState({ selectedTab: 'tab2' })} > - + ); } diff --git a/types/expo__vector-icons/index.d.ts b/types/expo__vector-icons/index.d.ts index 529142c0e9..7a7ac587ec 100644 --- a/types/expo__vector-icons/index.d.ts +++ b/types/expo__vector-icons/index.d.ts @@ -1,13 +1,16 @@ -// Type definitions for @expo/vector-icons 6.2 +// Type definitions for @expo/vector-icons 9.0 // Project: https://github.com/expo/vector-icons // Definitions by: Hyeonsu Lee +// Robert Ying // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; import { TextProps } from 'react-native'; +import { Icon } from 'react-native-vector-icons/Icon'; export { createIconSet, createIconSetFromFontello, createIconSetFromIcoMoon } from 'react-native-vector-icons'; +export { Icon as AntDesign }; export { default as Entypo } from 'react-native-vector-icons/Entypo'; export { default as EvilIcons } from 'react-native-vector-icons/EvilIcons'; export { default as Feather } from 'react-native-vector-icons/Feather'; diff --git a/types/fastify-rate-limit/fastify-rate-limit-tests.ts b/types/fastify-rate-limit/fastify-rate-limit-tests.ts new file mode 100644 index 0000000000..ee79951f48 --- /dev/null +++ b/types/fastify-rate-limit/fastify-rate-limit-tests.ts @@ -0,0 +1,22 @@ +import fastifyRateLimit = require("fastify-rate-limit"); +import * as IORedis from 'ioredis'; +import { FastifyRequest, DefaultQuery } from "fastify"; +import { IncomingMessage } from "http"; + +fastifyRateLimit(); + +const fastifyRateLimitOptions: fastifyRateLimit.FastifyRateLimitOptions> = { + max: 3, + timeWindow: 5000, + cache: 10000, + whitelist: ['127.0.0.1'], + redis: new IORedis({ host: '127.0.0.1' }), + skipOnError: true, // default false + keyGenerator: (req) => { + return req.headers['x-real-ip'] + || req.headers['x-client-ip'] + || req.headers['x-forwarded-for'] + || req.params.test + || req.ip; + }, +}; diff --git a/types/fastify-rate-limit/index.d.ts b/types/fastify-rate-limit/index.d.ts new file mode 100644 index 0000000000..888611ad72 --- /dev/null +++ b/types/fastify-rate-limit/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for fastify-rate-limit 2.0 +// Project: https://github.com/fastify/fastify-rate-limit#readme +// Definitions by: Christian D +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Redis } from "ioredis"; +import { FastifyRequest } from "fastify"; +import { IncomingMessage } from "http"; + +declare function fastifyRateLimit(): void; + +declare namespace fastifyRateLimit { + interface FastifyRateLimitOptions> { + /** + * Is the maximum number of requests a single client can perform inside a + * timeWindow. + * + * default: 1000 + */ + max?: number; + + /** + * The duration of the time window, can be expressed in milliseconds (as a + * number) or as a string, see ms too see the supported formats + * + * default: 1000 * 60 + */ + timeWindow?: number; + + /** + * This plugin internally uses a lru cache to handle the clients, you can + * change the size of the cache with this option. + * + * default: 5000 + */ + cache?: number; + + /** + * Array of string of ips to exclude from rate limiting. + * + * default: [] + */ + whitelist?: string[]; + + /** + * By default this plugins uses an in-memory store, which is fast but if + * you application works on more than one server it is useless, since the + * data is store locally. You can pass a Redis client here and magically + * the issue is solved. To achieve the maximum speed, this plugins requires + * the use of ioredis. + * + * default: null + */ + redis?: Redis; + + /** + * If `true` it will skip errors generated by the storage (eg, redis not + * reachable). + * + * default: false + */ + skipOnError?: boolean; + + /** + * Function to generate a unique identifier for each incoming request. + * + * default: (req) => req.ip + */ + keyGenerator?: (req: T) => string; + } +} + +export = fastifyRateLimit; diff --git a/types/fastify-rate-limit/package.json b/types/fastify-rate-limit/package.json new file mode 100644 index 0000000000..e8c68ab969 --- /dev/null +++ b/types/fastify-rate-limit/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "fastify": "^1.11.2" + } +} diff --git a/types/fastify-rate-limit/tsconfig.json b/types/fastify-rate-limit/tsconfig.json new file mode 100644 index 0000000000..5dc0e91ea2 --- /dev/null +++ b/types/fastify-rate-limit/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "fastify-rate-limit-tests.ts"], + "exclude": ["node-modules"] +} diff --git a/types/fastify-rate-limit/tslint.json b/types/fastify-rate-limit/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/forge-apis/README.md b/types/forge-apis/README.md new file mode 100644 index 0000000000..9da41d3d61 --- /dev/null +++ b/types/forge-apis/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/forge-apis` + +# Summary +This package contains type definitions for Forge Node.js SDK (https://github.com/Autodesk-Forge/forge-api-nodejs-client). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-apis + +Additional Details + * Last updated: Fri, 11 Jan 2019 10:39:13 GMT + * Dependencies: @types/three + * Global values: none + +# Credits +Forge Partner Development diff --git a/types/forge-apis/forge-apis-tests.ts b/types/forge-apis/forge-apis-tests.ts new file mode 100644 index 0000000000..d7031facb9 --- /dev/null +++ b/types/forge-apis/forge-apis-tests.ts @@ -0,0 +1,13 @@ +import { AuthClientTwoLegged, AuthClientThreeLegged, BucketsApi, HubsApi, FoldersApi, DerivativesApi } from 'forge-apis'; + +const authClientTwoLegged: AuthClientTwoLegged = new AuthClientTwoLegged("", "", []); + +const authClientThreeLegged: AuthClientThreeLegged = new AuthClientThreeLegged("", "", "", []); + +const bucketsApi: BucketsApi = new BucketsApi(); + +const hubsApi: HubsApi = new HubsApi(); + +const foldersApi: FoldersApi = new FoldersApi(); + +const derivativesApi: DerivativesApi = new DerivativesApi(); diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts new file mode 100644 index 0000000000..07dca58812 --- /dev/null +++ b/types/forge-apis/index.d.ts @@ -0,0 +1,193 @@ +// Type definitions for Forge-apis 0.4 +// Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client +// Definitions by: Autodesk Forge Partner Development +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// + +export class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); + + authenticate(): Promise; + getCredentials(): AuthToken; + setCredentials(credentials: AuthToken): void; + isAuthorized(): boolean; +} + +export class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: AuthToken): Promise; +} + +export interface ApiResponse { + body: any; + headers: any; + statusCode: number; +} + +export interface ApiError { + statusCode: number; + statusMessage: string; +} + +export class BucketsApi { + constructor(); + + createBucket(postBuckets: object, opts: object, credentials: AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: AuthToken): Promise; + getBuckets(options: object, credentials: AuthToken): Promise; +} + +export class HubsApi { + constructor(); + + getHub(hubId: string, opts: object, credentials: AuthToken): Promise; + getHubs(opts: object, credentials: AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: AuthToken): Promise; +} + +export class FoldersApi { + constructor(); + + getFolderContents(projectId: string, folderId: string, opts: object, credentials: AuthToken): Promise; +} + +export interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; +} + +export interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; +} + +export interface JobPayloadOutput { + formats: JobPayloadItem[]; +} + +export interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }; + format?: string; + exportColor?: boolean; + exportFileStructure?: string; +} + +export class DerivativesApi { + constructor(); + + deleteManifest(urn: string, credentials: AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: AuthToken): Promise; + getFormats(opts: object, credentials: AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: AuthToken): Promise; +} + +export interface Credentials { + client_id: string; + client_secret: string; + grant_type: string; + scope?: string; +} + +export interface AuthToken { + access_token: string; + expires_in: number; + token_type: string; + refresh_token?: string; +} + +export namespace Dm { + interface BucketResponse { + bucketKey: string; + bucketOwner: string; + createdDate: number; + permissions: Array<{ + access: string; + authId: string; + }>; + policyKey: string; + } + + interface ItemResponse { + data: any[]; + included: Item[]; + jsonapi: { + version: string; + }; + links: any; + } + + interface Item { + attributes: { + createTime: string; + createUserId: string; + displayName: string; + extension: object; + fileType: string; + lastModifiedTime: string; + lastModifiedUserId: string; + mimeType: string; + name: string; + storageSize: number; + versionNumber: number; + }; + id: string; + links: { + self: { + href: string; + }; + }; + relationships: { + derivatives: { + data: { + id: string; + }, + meta: { + link: { + href: string; + } + } + }, + item: any; + refs: any; + storage: { + data: { + id: string; + type: string; + } + }; + thumbnail: any; + }; + type: string; + } +} diff --git a/types/forge-apis/tsconfig.json b/types/forge-apis/tsconfig.json new file mode 100644 index 0000000000..3e026ae2b1 --- /dev/null +++ b/types/forge-apis/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "forge-apis-tests.ts" + ] +} diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/forge-apis/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/frisby/frisby-tests.ts b/types/frisby/frisby-tests.ts index d0bb27ff20..65a7315790 100644 --- a/types/frisby/frisby-tests.ts +++ b/types/frisby/frisby-tests.ts @@ -18,4 +18,9 @@ describe('Test Suite 1', () => { .expect('status', 418) .done(done); }); + + it('should handle jest matchers', () => { + const str = 'bar'; + expect(str).toHaveLength(3); + }); }); diff --git a/types/frisby/index.d.ts b/types/frisby/index.d.ts index 1bcd6fdabb..85151daa68 100644 --- a/types/frisby/index.d.ts +++ b/types/frisby/index.d.ts @@ -5,7 +5,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -/// +/// // #region Imports export import nodeFetch = require('node-fetch'); // Import all definitions from node-fetch. diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 4b8a69aa93..28590def30 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -34,7 +34,7 @@ const opts = { priorityRange: 5, autostart: false, evictionRunIntervalMillis: 200, - numTestsPerRun: 3, + numTestsPerEvictionRun: 3, softIdleTimeoutMillis: 100, idleTimeoutMillis: 5000 }; diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 80a3c0e9df..6bb537e9ba 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -43,7 +43,7 @@ export interface Options { priorityRange?: number; autostart?: boolean; evictionRunIntervalMillis?: number; - numTestsPerRun?: number; + numTestsPerEvictionRun?: number; softIdleTimeoutMillis?: number; idleTimeoutMillis?: number; } diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts index d393286dfe..f1df5d8f38 100644 --- a/types/google__maps/index.d.ts +++ b/types/google__maps/index.d.ts @@ -3107,7 +3107,7 @@ export interface QueryAutocompleteResult { * contains an `offset` value and a `length`. * These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired. */ - matched_substring: PredictionSubstring[]; + matched_substrings: PredictionSubstring[]; } /** A Radar Search request must include at least one of `keyword`, `name`, or `type`. */ diff --git a/types/happypack/happypack-tests.ts b/types/happypack/happypack-tests.ts new file mode 100644 index 0000000000..c0ab2d77cf --- /dev/null +++ b/types/happypack/happypack-tests.ts @@ -0,0 +1,7 @@ +import * as happyPack from 'happypack'; + +const ref: happyPack = new happyPack({ + id: '1', + threads: 1, + loaders: ['ts-loader'] +}); diff --git a/types/happypack/index.d.ts b/types/happypack/index.d.ts new file mode 100644 index 0000000000..13c212a3f8 --- /dev/null +++ b/types/happypack/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for happypack 5.0 +// Project: https://github.com/amireh/happypack +// Definitions by: Akash Vishwakarma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Plugin } from 'webpack'; + +export = happypack; + +declare namespace happypack { + interface PluginOptions { + id?: string; + threads?: number; + loaders: any; + } +} + +declare class happypack extends Plugin { + constructor(options: happypack.PluginOptions); +} diff --git a/types/happypack/tsconfig.json b/types/happypack/tsconfig.json new file mode 100644 index 0000000000..bfd5e35551 --- /dev/null +++ b/types/happypack/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", + "happypack-tests.ts" + ] +} \ No newline at end of file diff --git a/types/happypack/tslint.json b/types/happypack/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/happypack/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/http-aws-es/http-aws-es-tests.ts b/types/http-aws-es/http-aws-es-tests.ts index df432dbab4..18ae2b666c 100644 --- a/types/http-aws-es/http-aws-es-tests.ts +++ b/types/http-aws-es/http-aws-es-tests.ts @@ -1,42 +1,43 @@ -import { EnvironmentCredentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; import { Client } from "elasticsearch"; import HttpAmazonESConnector = require("http-aws-es"); new Client({ - amazonES: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - amazonES: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); -const myCredentials = new EnvironmentCredentials("AWS"); +const myCredentials = new AWS.EnvironmentCredentials("AWS"); + new Client({ - amazonES: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - amazonES: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index 91e12604f8..2a6ca11629 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-aws-es 1.1 +// Type definitions for http-aws-es 6.0 // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,18 +7,11 @@ /// import * as e from "elasticsearch"; -import { Credentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; declare module "elasticsearch" { - interface AmazonESOptions { - accessKey?: string; - credentials?: Credentials; - region: string; - secretKey?: string; - } - interface ConfigOptions { - amazonES?: AmazonESOptions; + awsConfig?: AWS.Config; } } diff --git a/types/http-cache-semantics/http-cache-semantics-tests.ts b/types/http-cache-semantics/http-cache-semantics-tests.ts new file mode 100644 index 0000000000..73de43b370 --- /dev/null +++ b/types/http-cache-semantics/http-cache-semantics-tests.ts @@ -0,0 +1,19 @@ +const req = { url: 'https://foo.bar', method: 'GET', headers: { foo: 'bar' } }; +const res = { status: 200, headers: { foo: 'bar' } }; + +import CachePolicy = require('http-cache-semantics'); + +const policy = new CachePolicy(req, res); +new CachePolicy(req, res, { shared: true }); +new CachePolicy(req, res, { cacheHeuristic: 0.1 }); +new CachePolicy(req, res, { immutableMinTimeToLive: 24 * 3600 * 1000 }); +new CachePolicy(req, res, { ignoreCargoCult: false }); +new CachePolicy(req, res, { trustServerDate: true }); + +policy.storable(); // $ExpectType boolean +policy.satisfiesWithoutRevalidation(req); // $ExpectType boolean +policy.responseHeaders(); // $ExpectType Headers +policy.timeToLive(); // $ExpectType number +CachePolicy.fromObject(policy.toObject()); // $ExpectType CachePolicy +policy.revalidationHeaders(req); // $ExpectType Headers +policy.revalidatedPolicy(req, res); // $ExpectType RevalidationPolicy diff --git a/types/http-cache-semantics/index.d.ts b/types/http-cache-semantics/index.d.ts new file mode 100644 index 0000000000..40545f3e0a --- /dev/null +++ b/types/http-cache-semantics/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for http-cache-semantics 4.0 +// Project: https://github.com/kornelski/http-cache-semantics#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = CachePolicy; + +declare class CachePolicy { + constructor(req: CachePolicy.Request, res: CachePolicy.Response, options?: CachePolicy.Options); + + /** + * Returns `true` if the response can be stored in a cache. + * If it's `false` then you MUST NOT store either the request or the response. + */ + storable(): boolean; + + /** + * This is the most important method. Use this method to check whether the cached response is still fresh + * in the context of the new request. + * + * If it returns `true`, then the given `request` matches the original response this cache policy has been + * created with, and the response can be reused without contacting the server. Note that the old response + * can't be returned without being updated, see `responseHeaders()`. + * + * If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), + * or may require to be refreshed first (see `revalidationHeaders()`). + */ + satisfiesWithoutRevalidation(newRequest: CachePolicy.Request): boolean; + + /** + * Returns updated, filtered set of response headers to return to clients receiving the cached response. + * This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) + * and update response's `Age` to avoid doubling cache time. + * + * @example + * cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); + */ + responseHeaders(): CachePolicy.Headers; + + /** + * Returns approximate time in milliseconds until the response becomes stale (i.e. not fresh). + * + * After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, + * there are exceptions, e.g. a client can explicitly allow stale responses, so always check with + * `satisfiesWithoutRevalidation()`. + */ + timeToLive(): number; + + /** + * Chances are you'll want to store the `CachePolicy` object along with the cached response. + * `obj = policy.toObject()` gives a plain JSON-serializable object. + */ + toObject(): CachePolicy.CachePolicyObject; + + /** + * `policy = CachePolicy.fromObject(obj)` creates an instance from object created by `toObject()`. + */ + static fromObject(obj: CachePolicy.CachePolicyObject): CachePolicy; + + /** + * Returns updated, filtered set of request headers to send to the origin server to check if the cached + * response can be reused. These headers allow the origin server to return status 304 indicating the + * response is still fresh. All headers unrelated to caching are passed through as-is. + * + * Use this method when updating cache from the origin server. + * + * @example + * updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); + */ + revalidationHeaders(newRequest: CachePolicy.Request): CachePolicy.Headers; + + /** + * Use this method to update the cache after receiving a new response from the origin server. + */ + revalidatedPolicy( + revalidationRequest: CachePolicy.Request, + revalidationResponse: CachePolicy.Response + ): CachePolicy.RevalidationPolicy; +} + +declare namespace CachePolicy { + interface Request { + url?: string; + method?: string; + headers: Headers; + } + + interface Response { + status?: number; + headers: Headers; + } + + interface Options { + /** + * If `true`, then the response is evaluated from a perspective of a shared cache (i.e. `private` is not + * cacheable and `s-maxage` is respected). If `false`, then the response is evaluated from a perspective + * of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). + * `true` is recommended for HTTP clients. + * @default true + */ + shared?: boolean; + /** + * A fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), + * e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. + * @default 0.1 + */ + cacheHeuristic?: number; + /** + * A number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. + * Note that [per RFC](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension) + * these can become stale, so `max-age` still overrides the default. + * @default 24*3600*1000 (24h) + */ + immutableMinTimeToLive?: number; + /** + * If `true`, common anti-cache directives will be completely ignored if the non-standard `pre-check` + * and `post-check` directives are present. These two useless directives are most commonly found + * in bad StackOverflow answers and PHP's "session limiter" defaults. + * @default false + */ + ignoreCargoCult?: boolean; + /** + * If `false`, then server's `Date` header won't be used as the base for `max-age`. This is against the RFC, + * but it's useful if you want to cache responses with very short `max-age`, but your local clock + * is not exactly in sync with the server's. + * @default true + */ + trustServerDate?: boolean; + } + + interface CachePolicyObject { + v: number; + t: number; + sh: boolean; + ch: number; + imm: number; + st: number; + resh: Headers; + rescc: { [key: string]: string }; + m: string; + u?: string; + h?: string; + a: boolean; + reqh: Headers | null; + reqcc: { [key: string]: string }; + } + + interface Headers { + [header: string]: string | string[] | undefined; + } + + interface RevalidationPolicy { + /** + * A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace + * the old cached `CachePolicy` with the new one. + */ + policy: CachePolicy; + /** + * Boolean indicating whether the response body has changed. + * + * - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old + * cached response body. + * - If `true`, you should use new response's body (if present), or make another request to the origin + * server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get + * the new resource. + */ + modified: boolean; + matches: boolean; + } +} diff --git a/types/http-cache-semantics/tsconfig.json b/types/http-cache-semantics/tsconfig.json new file mode 100644 index 0000000000..9940b3d2e6 --- /dev/null +++ b/types/http-cache-semantics/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", + "http-cache-semantics-tests.ts" + ] +} diff --git a/types/http-cache-semantics/tslint.json b/types/http-cache-semantics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-cache-semantics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 8f5e7b7a2a..4ecf403a6f 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -488,7 +488,6 @@ export interface BooleanSchema extends AnySchema { /** * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion * (when not in strict() mode) to be matched in a case insensitive manner. - * @param enabled */ insensitive(enabled?: boolean): this; } @@ -792,6 +791,11 @@ export interface ObjectSchema extends AnySchema { */ length(limit: number): this; + /** + * Requires the object to be a Joi schema instance. + */ + schema(): this; + /** * Specify validation rules for unknown keys matching a pattern. * diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index af85cab0ac..4dbc784756 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -706,6 +706,8 @@ objSchema = objSchema.nand(str, str); objSchema = objSchema.nand(str, str, str); objSchema = objSchema.nand(strArr); +objSchema = objSchema.schema(); + objSchema = objSchema.or(str); objSchema = objSchema.or(str, str); objSchema = objSchema.or(str, str, str); diff --git a/types/jquery.soap/index.d.ts b/types/jquery.soap/index.d.ts index 36674a677b..9a802163e4 100644 --- a/types/jquery.soap/index.d.ts +++ b/types/jquery.soap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery.SOAP 1.6.7 +// Type definitions for jQuery.SOAP 1.7 // Project: https://github.com/doedje/jquery.soap // Definitions by: Roland Greim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ @@ -72,6 +72,7 @@ declare namespace JQuerySOAP { SOAPHeader?: Object; statusCode?: Object; success?: (SOAPResponse: SOAPResponse) => void; + timeout?: number; url?: string; wss?: Object; } diff --git a/types/jquery.soap/tslint.json b/types/jquery.soap/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/jquery.soap/tslint.json +++ b/types/jquery.soap/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index c712187559..4b65740f36 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -27,7 +27,7 @@ interface RequestParams { export class RequestResult { } -export class Request implements Promise { +export class Request implements PromiseLike { constructor(chatter: Chatter, params: RequestParams); batchParams(): BatchRequestParams; @@ -36,16 +36,12 @@ export class Request implements Promise { stream(): Stream; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; thenCall(callback?: (err: Error, records: T) => void): Query; - - readonly [Symbol.toStringTag]: 'Promise'; } export class Resource extends Request { diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index c6aec12e7e..88dbdaa52d 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -112,21 +112,17 @@ interface DeployOptions { singlePackage?: boolean; } -export class AsyncResultLocator extends EventEmitter implements Promise { +export class AsyncResultLocator extends EventEmitter implements PromiseLike { check(callback?: Callback): Promise complete(callback?: Callback): Promise poll(interval: number, timeout: number): void; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; - - readonly [Symbol.toStringTag]: "Promise"; } export class DeployResultLocator extends AsyncResultLocator {} diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index 08ea888062..45442b91dc 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -615,7 +615,7 @@ async function testChatter(conn: sf.Connection): Promise { const feedResource: sf.Resource = chatter.resource('/feed-elements'); - const feedCreateRequest: any = await (feedResource.create({ + const feedCreateRequest: any = await feedResource.create({ body: { messageSegments: [{ type: 'Text', @@ -624,13 +624,13 @@ async function testChatter(conn: sf.Connection): Promise { }, feedElementType: 'FeedItem', subjectId: 'me' - }) as Promise); + }); console.log(`feedCreateRequest.id: ${feedCreateRequest.id}`); const itemLikesUrl = `/feed-elements/${feedCreateRequest.id}/capabilities/chatter-likes/items`; const itemsLikeResource: sf.Resource = chatter.resource(itemLikesUrl); - const itemsLikeCreateResult: sf.RequestResult = await (itemsLikeResource.create('') as Promise); + const itemsLikeCreateResult: sf.RequestResult = await itemsLikeResource.create(''); console.log(`itemsLikeCreateResult['likedItem']: ${itemsLikeCreateResult as any['likedItem']}`); } diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index 43829466b8..12201695b9 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODOs "array-type": false, + "await-promise": [true, "Request"], "ban-types": false, "eofline": false, "max-line-length": false, diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 05d9c50aa6..91f0d455cc 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -7,6 +7,7 @@ // Benjamin Dobson // Be Birchall // Daniel Cassidy +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -264,6 +265,13 @@ declare namespace jwplayer { reason: 'auto' | 'api' | 'initial choice'; } + interface CastParam { + available: boolean; + active: boolean; + deviceName: string; + type: 'cast'; + } + interface EventParams { adClick: AdProgressParam; adCompanions: AdCompanionsParam; @@ -277,6 +285,7 @@ declare namespace jwplayer { adPlay: AdPlayParam; adPause: AdPlayParam; adTime: AdTimeParam; + cast: CastParam; meta: MetadataParam; audioTracks: AudioTracksParam; audioTrackChanged: AudioTrackChangedParam; diff --git a/types/jws/index.d.ts b/types/jws/index.d.ts index fdbf1851c4..6c9d7194f5 100644 --- a/types/jws/index.d.ts +++ b/types/jws/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jws 3.1 +// Type definitions for jws 3.2 // Project: https://github.com/brianloveswords/node-jws // Definitions by: Justin Beckwith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -145,7 +145,8 @@ export interface VerifyOptions { export type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'ES256' | 'ES384' | - 'ES512' | 'none'; + 'ES512' | 'PS256' | 'PS384' | 'PS512' | + 'none'; export interface Header { alg: Algorithm; diff --git a/types/koa-bouncer/index.d.ts b/types/koa-bouncer/index.d.ts index 7b881f2b5c..af3a8b6693 100644 --- a/types/koa-bouncer/index.d.ts +++ b/types/koa-bouncer/index.d.ts @@ -7,7 +7,7 @@ import { Middleware, Context } from 'koa'; declare namespace KoaBouncer { - export class ValidatorError extends Error { + export class ValidationError extends Error { name: string; message: string; bouncer: { @@ -88,4 +88,4 @@ declare module "koa" { } } -export = KoaBouncer; \ No newline at end of file +export = KoaBouncer; diff --git a/types/koa-session/index.d.ts b/types/koa-session/index.d.ts index 08e6e66f70..512b888e1c 100644 --- a/types/koa-session/index.d.ts +++ b/types/koa-session/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for koa-session 5.7 +// Type definitions for koa-session 5.10 // Project: https://github.com/koajs/session // Definitions by: Yu Hsin Lu // Tomek Łaziuk +// Hiroshi Ioka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /* =================== USAGE =================== @@ -16,6 +17,9 @@ =============================================== */ import Koa = require("koa"); +import Cookies = require("cookies"); + +type Omit = Pick>; declare namespace session { /** @@ -108,7 +112,7 @@ declare namespace session { hash(sess: any): string; } - interface opts { + interface opts extends Omit { /** * cookie key (default is koa:sess) */ @@ -121,21 +125,6 @@ declare namespace session { */ maxAge?: number | "session"; - /** - * can overwrite or not (default true) - */ - overwrite: boolean; - - /** - * httpOnly or not (default true) - */ - httpOnly: boolean; - - /** - * signed or not (default true) - */ - signed: boolean; - /** * custom encode method */ diff --git a/types/koa-session/koa-session-tests.ts b/types/koa-session/koa-session-tests.ts index a647b43e42..4930a6f1c2 100644 --- a/types/koa-session/koa-session-tests.ts +++ b/types/koa-session/koa-session-tests.ts @@ -37,6 +37,7 @@ app.use(session({ console.log(key); }, }, + path: "/", }, app)); app.use((ctx, next) => { diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts index 24e85e1674..049c655f5f 100644 --- a/types/koa2-session-redis/index.d.ts +++ b/types/koa2-session-redis/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/lonord/koa2-session-redis // Definitions by: Dima Mukhin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as Redis from 'redis'; import * as session from 'koa-session'; diff --git a/types/lory.js/index.d.ts b/types/lory.js/index.d.ts index dd37fb8efa..82c1f6fbc6 100644 --- a/types/lory.js/index.d.ts +++ b/types/lory.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lory 2.2.1 +// Type definitions for lory 2.5.3 // Project: https://github.com/meandmax/lory/ // Definitions by: kubosho // philip bulley @@ -80,6 +80,11 @@ interface LoryOptions { * cubic bezier easing functions: http://easings.net/de (default: 'cubic-bezier(0.455, 0.03, 0.515, 0.955)'). */ ease?: string; + + /** + * the slide index to show when the slider is initialized ( default: 0 ) + */ + initialIndex?: number; /** * if slider reached the last slide, with next click the slider goes back to the startindex (default: false). diff --git a/types/lory.js/lory.js-tests.ts b/types/lory.js/lory.js-tests.ts index 616073f180..f3ca0464c2 100644 --- a/types/lory.js/lory.js-tests.ts +++ b/types/lory.js/lory.js-tests.ts @@ -19,6 +19,7 @@ import { lory } from 'lory.js'; rewindSpeed: 600, snapBackSpeed: 200, ease: 'ease', + initialIndex: 0, rewind: true, infinite: false, classNameFrame: 'js_frame', diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 890d0731ad..b5f1134fb5 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -5,6 +5,7 @@ // Jonathan Siebern // Matt R. Wilson // Pietro Vismara +// Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -467,11 +468,11 @@ export interface ZoneOffsetOptions { } export class Zone { - static offsetName(ts: number, options?: ZoneOffsetOptions): string; - static isValid: boolean; - static name: string; - static type: string; - static universal: boolean; + offsetName(ts: number, options?: ZoneOffsetOptions): string; + isValid: boolean; + name: string; + type: string; + universal: boolean; equals(other: Zone): boolean; offset(ts: number): number; } diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index 3cadfa5779..df5481094b 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -1,4 +1,4 @@ -import { DateTime, Duration, Interval, Info, Settings, IANAZone } from 'luxon'; +import { DateTime, Duration, Interval, Info, Settings, IANAZone, Zone, ZoneOffsetOptions } from 'luxon'; /* DateTime */ const dt = DateTime.local(2017, 5, 15, 8, 30); @@ -285,3 +285,21 @@ dur.reconfigure({ conversionAccuracy: 'longterm' }); // $ExpectType Duration start.until(end); // $ExpectType Interval i.toDuration(['years', 'months', 'days']); // $ExpectType Duration + +/* Sample Zone Implementation */ +class SampleZone extends Zone { + readonly isValid = false; + readonly name = 'Sample'; + readonly type = 'Example'; + readonly universal = true; + + offsetName(ts: number, options?: ZoneOffsetOptions) { + return 'SampleZone'; + } + equals(other: Zone) { + return other.name === this.name; + } + offset(ts: number) { + return 0; + } +} diff --git a/types/mapbox__s3urls/index.d.ts b/types/mapbox__s3urls/index.d.ts new file mode 100644 index 0000000000..523cb0fc07 --- /dev/null +++ b/types/mapbox__s3urls/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for mapbox__s3urls 1.5 +// Project: https://github.com/mapbox/s3urls +// Definitions by: Sebastian Vera +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// tslint:disable-next-line no-single-declare-module +declare module "@mapbox/s3urls" { + function fromUrl( + url: string + ): { Bucket: string | undefined; Key: string | undefined }; + + function toUrl( + bucket: string, + key: string + ): { + s3: string; + "bucket-in-path": string; + "bucket-in-host": string; + }; + + function convert( + url: string, + to: "s3" | "bucket-in-path" | "bucket-in-host" + ): string; + + function signed( + url: string, + expires: number, + cb: (err: Error | undefined, url: string) => void + ): void; + + function valid(url: string): boolean; +} diff --git a/types/mapbox__s3urls/mapbox__s3urls-tests.ts b/types/mapbox__s3urls/mapbox__s3urls-tests.ts new file mode 100644 index 0000000000..7a50fdcfac --- /dev/null +++ b/types/mapbox__s3urls/mapbox__s3urls-tests.ts @@ -0,0 +1,15 @@ +import * as s3urls from "@mapbox/s3urls"; + +s3urls.toUrl("bucket", "key"); // $ExpectType { s3: string; "bucket-in-path": string; "bucket-in-host": string; } +s3urls.toUrl("bucket", "key")["s3"]; // $ExpectType string +s3urls.toUrl("bucket", "key")["bucket-in-host"]; // $ExpectType string +s3urls.toUrl("bucket", "key")["bucket-in-path"]; // $ExpectType string + +s3urls.valid("s3://bucket/key"); // $ExpectType boolean +s3urls.valid("invalid"); // $ExpectType boolean + +s3urls.convert("s3://bucket/key", "s3"); // $ExpectType string +s3urls.convert("s3://bucket/key", "bucket-in-path"); // $ExpectType string +s3urls.convert("s3://bucket/key", "bucket-in-host"); // $ExpectType string + +s3urls.fromUrl("s3://bucket/key"); // $ExpectType object diff --git a/types/mapbox__s3urls/tsconfig.json b/types/mapbox__s3urls/tsconfig.json new file mode 100644 index 0000000000..9c3d217340 --- /dev/null +++ b/types/mapbox__s3urls/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "paths": { + "@mapbox/s3urls": ["mapbox__s3urls"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mapbox__s3urls-tests.ts"] +} diff --git a/types/mapbox__s3urls/tslint.json b/types/mapbox__s3urls/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mapbox__s3urls/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mem-cache/index.d.ts b/types/mem-cache/index.d.ts new file mode 100644 index 0000000000..df2a0db47d --- /dev/null +++ b/types/mem-cache/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for mem-cache 1.0 +// Project: https://github.com/silviom/node-mem-cache +// Definitions by: Pedro Mutter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { EventEmitter } from 'events'; + +interface CacheOptions { + timeout?: number; + doesNotRenewTimeout?: boolean; + timeoutDisabled?: boolean; +} + +declare class Cache extends EventEmitter { + keys: string[]; + length: number; + + constructor(options?: number | CacheOptions); + + set(key: string, value: any, timeout?: number): void; + get(key: string): any; + remove(key: string): void; + clean(): void; +} + +export = Cache; diff --git a/types/mem-cache/mem-cache-tests.ts b/types/mem-cache/mem-cache-tests.ts new file mode 100644 index 0000000000..747ffd75c2 --- /dev/null +++ b/types/mem-cache/mem-cache-tests.ts @@ -0,0 +1,10 @@ +import Cache = require('mem-cache'); + +const cache = new Cache(); // $ExpectType Cache + +cache.set('foo', 'bar'); // $ExpectType void +cache.get('foo'); // $ExpectType any +cache.remove('foo'); // $ExpectType void +cache.clean(); // $ExpectType void +cache.length; // $ExpectType number +cache.keys; // $ExpectType string[] diff --git a/types/mem-cache/tsconfig.json b/types/mem-cache/tsconfig.json new file mode 100644 index 0000000000..3c3a2e701a --- /dev/null +++ b/types/mem-cache/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mem-cache-tests.ts" + ], + "baseUrl": "types", + "typeRoots": ["types"] +} diff --git a/types/mem-cache/tslint.json b/types/mem-cache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mem-cache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mermaid/mermaid-tests.ts b/types/mermaid/mermaid-tests.ts index 6d5b218ce4..a94355fb67 100644 --- a/types/mermaid/mermaid-tests.ts +++ b/types/mermaid/mermaid-tests.ts @@ -13,7 +13,7 @@ mermaid.initialize(config); // mermaidAPI usage const { mermaidAPI } = mermaid; -mermaidAPI.initalize({}); +mermaidAPI.initialize({}); const element = document.querySelector("#graphDiv")!; diff --git a/types/mermaid/mermaidAPI.d.ts b/types/mermaid/mermaidAPI.d.ts index 11077d88c4..127a679dae 100644 --- a/types/mermaid/mermaidAPI.d.ts +++ b/types/mermaid/mermaidAPI.d.ts @@ -240,7 +240,7 @@ declare namespace mermaidAPI { function parse(text: string): any; - function initalize(options: Config): void; + function initialize(options: Config): void; function getConfig(): Config; } diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b7d3b5d9c6..d9f9d789f0 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -16,6 +16,8 @@ // Dan Manastireanu // stablio // Emmanuel Gautier +// Frontend Monster +// Ming Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -316,6 +318,16 @@ declare module "mongoose" { readyState: number; } + /** + * Connection optional settings. + * + * see + * https://mongoosejs.com/docs/api.html#mongoose_Mongoose-connect + * and + * http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html + * for all available options. + * + */ interface ConnectionOptionsBase { /** database Name for Mongodb Atlas Connection */ dbName?: string; @@ -339,11 +351,13 @@ declare module "mongoose" { poolSize?: number; /** Reconnect on error (default: true) */ autoReconnect?: boolean; - /** TCP KeepAlive on the socket with a X ms delay before start (default: 0). */ - keepAlive?: number; - /** TCP Connection timeout setting (default: 0) */ + /** TCP Connection keep alive enabled (default: true) */ + keepAlive?: boolean; + /** The number of milliseconds to wait before initiating keepAlive on the TCP socket (default 30000) */ + keepAliveInitialDelay?: number; + /** TCP Connection timeout setting (default: 30000) */ connectTimeoutMS?: number; - /** TCP Socket timeout setting (default: 0) */ + /** TCP Socket timeout setting (default: 360000) */ socketTimeoutMS?: number; /** If the database authentication is dependent on another databaseName. */ authSource?: string; @@ -1310,7 +1324,7 @@ declare module "mongoose" { * @param kind optional kind property for the error * @returns the current ValidationError, with all currently invalidated paths */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): Error.ValidationError | boolean; + invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): Error.ValidationError | boolean; /** Returns true if path was directly set and modified, else false. */ isDirectModified(path: string): boolean; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 8e6a60fdc7..30b5b51a84 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -726,6 +726,7 @@ doc.execPopulate().then(function (arg) { doc.get('path', Number); doc.init(doc).init(doc, {}); doc.inspect(); +doc.invalidate('path', new Error('hi')).toString(); doc.invalidate('path', new Error('hi'), 999).toString(); doc.isDirectModified('path').valueOf(); doc.isInit('path').valueOf(); diff --git a/types/moo/index.d.ts b/types/moo/index.d.ts index fd53f98e0a..2dd1a4b4db 100644 --- a/types/moo/index.d.ts +++ b/types/moo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for moo 0.4 +// Type definitions for moo 0.5 // Project: https://github.com/tjvr/moo#readme // Definitions by: Nikita Litvin // Jörg Vehlow @@ -11,6 +11,15 @@ export as namespace moo; */ export const error: { error: true }; +/** + * Reserved token for indicating a fallback rule. + */ +export const fallback: { fallback: true }; + +export type TypeMapper = (x: string) => string; + +export function keywords(kws: {[k: string]: string | string[]}): TypeMapper; + export function compile(rules: Rules): Lexer; export function states(states: {[x: string]: Rules}, start?: string): Lexer; @@ -45,9 +54,11 @@ export interface Rule { */ value?: (x: string) => string; - keywords?: { - [x: string]: string | string[] - }; + /** + * Used for mapping one set of types to another. + * See https://github.com/no-context/moo#keywords for an example + */ + type?: TypeMapper; } export interface Rules { [x: string]: RegExp | string | string[] | Rule | Rule[]; diff --git a/types/moo/moo-tests.ts b/types/moo/moo-tests.ts index c82bedd219..5cb9fa6f5b 100644 --- a/types/moo/moo-tests.ts +++ b/types/moo/moo-tests.ts @@ -20,20 +20,21 @@ lexer = moo.compile({ lexer = moo.compile({ IDEN: { - match: /[a-zA-Z]+/, keywords: { + match: /[a-zA-Z]+/, + type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'reloacows'] - } + }) }, SPACE: { match: /\s+/, lineBreaks: true } }); lexer = moo.compile({ name: { - match: /[a-zA-Z]+/, keywords: { + match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', - } + }) } }); diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 891186f7ee..085ab122c1 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -288,6 +288,12 @@ export declare class RequestError implements Error { public name: string; public message: string; public code: string; + public number?: number; + public state?: number; + public class?: number; + public lineNumber?: number; + public serverName?: string; + public procName?: string; } export declare class Transaction extends events.EventEmitter { diff --git a/types/mui-datatables/index.d.ts b/types/mui-datatables/index.d.ts new file mode 100644 index 0000000000..055406cc6f --- /dev/null +++ b/types/mui-datatables/index.d.ts @@ -0,0 +1,173 @@ +// Type definitions for mui-datatables 2.0 +// Project: https://github.com/gregnb/mui-datatable +// Definitions by: Jeroen "Favna" Claassens +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface MUIDataTableData { + index: number; + data: any[]; +} + +interface MUIDataTableStateRows { + data: string[]; + lookup: any; +} + +interface MUIDataTableState { + announceText: string | null; + activeColumn: string | null; + page: number; + rowsPerPage: number; + filterList: string[][]; + selectedRows: MUIDataTableStateRows; + expandedRows: MUIDataTableStateRows; + showResponsive: boolean; + searchText: string | null; + rowsPerPageOptions: number[]; +} + +interface MUIDataTableMeta { + rowIndex: number; + columnIndex: number; + columnData: MUIDataTableColumnOptions[]; + rowData: any[]; + tableData: MUIDataTableData[]; + tableState: MUIDataTableState; +} + +interface MUIDataTableCustomHeadRenderer extends MUIDataTableColumn { + index: number; +} + +interface MUIDataTableColumn { + name: string; + options?: MUIDataTableColumnOptions; +} + +interface MUIDataTableTextLabelsBody { + noMatch: string; + toolTip: string; +} + +interface MUIDataTableTextLabelsPagination { + next: string; + previous: string; + rowsPerPage: string; + displayRows: string; +} + +interface MUIDataTableTextLabelsToolbar { + search: string; + downloadCsv: string; + print: string; + viewColumns: string; + filterTable: string; +} + +interface MUIDataTableTextLabelsFilter { + all: string; + title: string; + reset: string; +} + +interface MUIDataTableTextLabelsViewColumns { + title: string; + titleAria: string; +} + +interface MUIDataTableTextLabelsSelectedRows { + text: string; + delete: string; + deleteAria: string; +} + +interface MUIDataTableTextLabels { + body: MUIDataTableTextLabelsBody; + pagination: MUIDataTableTextLabelsPagination; + toolbar: MUIDataTableTextLabelsToolbar; + filter: MUIDataTableTextLabelsFilter; + viewColumns: MUIDataTableTextLabelsViewColumns; + selectedRows: MUIDataTableTextLabelsSelectedRows; +} + +export interface MUIDataTableColumnOptions { + display?: 'true' | 'false' | 'excluded'; + filter?: boolean; + filterList?: string[]; + filterOptions?: string[]; + sort?: boolean; + sortDirection?: 'asc' | 'desc'; + download?: boolean; + hint?: string; + customHeadRender?: (columnMeta: MUIDataTableCustomHeadRenderer, updateDirection: (params: any) => any) => string; + customBodyRender?: (value: any, tableMeta: MUIDataTableMeta, updateValue: (s: any, c: any, p: any) => any) => string | React.ReactNode; + setCellProps?: (cellValue: string, rowIndex: number, columnIndex: number) => string; +} + +export interface MUIDataTableOptions { + page?: number; + count?: number; + serverSide?: boolean; + rowsSelected?: any[]; + filterType?: 'dropdown' | 'checkbox' | 'multiselect' | 'textField'; + textLabels?: MUIDataTableTextLabels; + pagination?: boolean; + selectableRows?: boolean; + IsRowSelectable?: (dataIndex: any) => boolean; + resizableColumns?: boolean; + expandableRows?: boolean; + renderExpandableRow?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => React.ReactNode; + customToolbar?: () => React.ReactNode; + customToolbarSelect?: () => React.ReactNode; + customFooter?: () => React.ReactNode; + customSort?: (data: any[], colIndex: number, order: string) => any[]; + elevation?: number; + caseSensitive?: boolean; + responsive?: 'stacked' | 'scroll'; + rowsPerPage?: number; + rowsPerPageOptions?: number[]; + rowHover?: boolean; + fixedHeader?: boolean; + sortFilterList?: boolean; + sort?: boolean; + filter?: boolean; + search?: boolean; + print?: boolean; + download?: boolean; + downloadOptions?: { filename: string; separator: string }; + viewColumns?: boolean; + onRowsSelect?: (currentRowsSelected: any[], rowsSelected: any[]) => void; + onRowsDelete?: (rowsDeleted: any[]) => void; + onRowClick?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => void; + onCellClick?: (colIndex: number, rowIndex: number) => void; + onChangePage?: (currentPage: number) => void; + onChangeRowsPerPage?: (numberOfRows: number) => void; + onSearchChange?: (searchText: string) => void; + onFilterChange?: (changedColumn: string, filterList: any[]) => void; + onColumnSortChange?: (changedColumn: string, direction: string) => void; + onColumnViewChange?: (changedColumn: string, action: string) => void; + onTableChange?: (action: string, tableState: object) => void; + setRowProps?: (row: any[], rowIndex: number) => any; +} + +export type MUIDataTableColumnDef = string | MUIDataTableColumn; + +export interface MuiDatatablesTableState { + page: number; + rowsPerPage: number; + filterList: any[]; +} + +export interface MUIDataTableProps { + title: string; + columns: MUIDataTableColumnDef[]; + data: any[]; + options?: MUIDataTableOptions; +} + +declare const MUIDataTable: React.ComponentType; + +export default MUIDataTable; diff --git a/types/mui-datatables/mui-datatables-tests.tsx b/types/mui-datatables/mui-datatables-tests.tsx new file mode 100644 index 0000000000..5ad018082e --- /dev/null +++ b/types/mui-datatables/mui-datatables-tests.tsx @@ -0,0 +1,83 @@ +import MUIDataTable, { MUIDataTableColumnDef, MUIDataTableOptions } from 'mui-datatables'; +import * as React from 'react'; + +const dataSimple: string[][] = [ + ['Joe James', 'Test Corp', 'Yonkers', 'NY'], + ['John Walsh', 'Test Corp', 'Hartford', 'CT'], + ['Bob Herm', 'Test Corp', 'Tampa', 'FL'], + ['James Houston', 'Test Corp', 'Dallas', 'TX'] +]; + +const columnWithOptions: MUIDataTableColumnDef[] = [ + { + name: 'Name', + options: { + display: 'true', + filter: true, + sort: true, + sortDirection: 'asc', + download: true, + } + } +]; + +const options: MUIDataTableOptions = { + filterType: 'checkbox', + responsive: 'scroll', + selectableRows: false, + elevation: 0, + rowsPerPageOptions: [5, 10, 20, 25, 50, 100], + downloadOptions: { + filename: 'filename.csv', + separator: ',' + }, + sortFilterList: false, + textLabels: { + body: { + noMatch: 'Sorry, no matching records found', + toolTip: 'Sort', + }, + pagination: { + next: 'Next Page', + previous: 'Previous Page', + rowsPerPage: 'Rows per page:', + displayRows: 'of', + }, + toolbar: { + search: 'Search', + downloadCsv: 'Download CSV', + print: 'Print', + viewColumns: 'View Columns', + filterTable: 'Filter Table', + }, + filter: { + all: 'All', + title: 'FILTERS', + reset: 'RESET', + }, + viewColumns: { + title: 'Show Columns', + titleAria: 'Show/Hide Table Columns', + }, + selectedRows: { + text: 'rows(s) selected', + delete: 'Delete', + deleteAria: 'Delete Selected Rows', + } + } +}; + +class MuiDataTable extends React.Component { + render() { + return ( + + ); + } +} + +; diff --git a/types/mui-datatables/tsconfig.json b/types/mui-datatables/tsconfig.json new file mode 100644 index 0000000000..280efbb284 --- /dev/null +++ b/types/mui-datatables/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mui-datatables-tests.tsx" + ] +} diff --git a/types/mui-datatables/tslint.json b/types/mui-datatables/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mui-datatables/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/multiparty/index.d.ts b/types/multiparty/index.d.ts index ca968fefcf..1dbb3e272b 100644 --- a/types/multiparty/index.d.ts +++ b/types/multiparty/index.d.ts @@ -19,6 +19,13 @@ export declare class Form extends events.EventEmitter { * @param callback */ parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; + + on(event: "part", listener: (part: Part) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "progress", listener: (bytesReceived: number, bytesExpected: number) => void): this; + on(event: "field", listener: (name: string, value: string) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; } export interface File { @@ -29,7 +36,7 @@ export interface File { /** * the filename that the user reports for the file */ - originalFileName: string; + originalFilename: string; /** * the absolute path of the uploaded file on disk */ @@ -44,7 +51,7 @@ export interface File { size: number; } -interface Part extends stream.Readable { +export interface Part extends stream.Readable { /** * the headers for this part. For example, you may be interested in content-type */ diff --git a/types/needle/index.d.ts b/types/needle/index.d.ts index 509e212c6e..af879cfacc 100644 --- a/types/needle/index.d.ts +++ b/types/needle/index.d.ts @@ -247,6 +247,7 @@ declare namespace needle { export type NeedleCallback = core.NeedleCallback; export type NeedleHttpVerbs = core.NeedleHttpVerbs; export type NeedleOptions = core.NeedleOptions; + export type NeedleResponse = core.NeedleResponse; export type ReadableStream = core.ReadableStream; /** diff --git a/types/needle/needle-tests.ts b/types/needle/needle-tests.ts index a216b1f686..fac7efa58c 100644 --- a/types/needle/needle-tests.ts +++ b/types/needle/needle-tests.ts @@ -73,14 +73,18 @@ function API_head() { function API_get() { // using promises + let resp: needle.NeedleResponse; + needle('get', 'google.com/search?q=syd+barrett') - .then((resp) => { + .then((_resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; }); // using callback - needle.get('google.com/search?q=syd+barrett', (err, resp) => { + needle.get('google.com/search?q=syd+barrett', (err, _resp) => { // if no http:// is found, Needle will automagically prepend it. + resp = _resp; // assign response }); } diff --git a/types/next-seo/index.d.ts b/types/next-seo/index.d.ts new file mode 100644 index 0000000000..8d7c487393 --- /dev/null +++ b/types/next-seo/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for next-seo 1.10 +// Project: https://github.com/garmeeh/next-seo#readme +// Definitions by: Thomas Kosiewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Component } from "react"; + +export interface NextSeoProps { + config: Config; +} + +export interface Config { + title?: string; + titleTemplate?: string; + description?: string; + canonical?: string; + + dangerouslySetAllPagesToNoIndex?: boolean; + noindex?: boolean; + + twitter?: Twitter; + facebook?: Facebook; + openGraph?: OpenGraph; +} + +export interface Twitter { + cardType?: string; + site?: string; + handle?: string; +} + +export interface Facebook { + appId?: number; +} + +export interface OpenGraph { + url?: string; + type?: string; + title?: string; + description?: string; + images?: ReadonlyArray; + defaultImageHeight?: number; + defaultImageWidth?: number; + locale?: string; + site_name?: string; + + profile?: OpenGraphProfile; + book?: OpenGraphBook; + article?: OpenGraphArticle; +} + +export interface OpenGraphImages { + url?: string; + width?: number; + height?: number; + alt?: string; +} + +export interface OpenGraphProfile { + firstName?: string; + lastName?: string; + username?: string; + gender?: string; +} + +export interface OpenGraphBook { + authors?: ReadonlyArray; + isbn?: string; + releaseDate?: string; + tags?: ReadonlyArray; +} + +export interface OpenGraphArticle { + publishedTime?: string; + modifiedTime?: string; + expirationTime?: string; + + authors?: ReadonlyArray; + section?: string; + tags?: ReadonlyArray; +} + +export default class NextSeo extends Component { } diff --git a/types/next-seo/next-seo-tests.ts b/types/next-seo/next-seo-tests.ts new file mode 100644 index 0000000000..3c2da4b032 --- /dev/null +++ b/types/next-seo/next-seo-tests.ts @@ -0,0 +1,48 @@ +import NextSeo from 'next-seo'; + +new NextSeo({ + config: { + canonical: "", + dangerouslySetAllPagesToNoIndex: false, + description: "", + facebook: { + appId: 0, + }, + noindex: false, + openGraph: { + book: { + authors: [""], + isbn: "", + releaseDate: "", + tags: [""], + }, + defaultImageHeight: 0, + defaultImageWidth: 0, + description: "", + images: [{ + alt: "", + height: 0, + url: "", + width: 0, + }], + locale: "", + profile: { + firstName: "", + gender: "", + lastName: "", + username: "", + }, + site_name: "", + title: "", + type: "", + url: "", + }, + title: "", + titleTemplate: "", + twitter: { + cardType: "", + handle: "", + site: "", + }, + }, +}); diff --git a/types/next-seo/tsconfig.json b/types/next-seo/tsconfig.json new file mode 100644 index 0000000000..faea26b9bc --- /dev/null +++ b/types/next-seo/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "next-seo-tests.ts" + ] +} diff --git a/types/next-seo/tslint.json b/types/next-seo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/next-seo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 9ac8985cdf..e0879e1c68 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -37,7 +37,7 @@ export interface NextDocumentContext exte * https://github.com/zeit/next.js/blob/7.0.0/server/document.js#L16 */ export interface DefaultDocumentIProps extends RenderPageResponse { - styles?: React.ReactNode; + styles?: React.ReactNode[]; } /** diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index bf7ccf036d..83d0a0e8a3 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -35,7 +35,9 @@ class MyDocumentDefault extends Document { } class MyDoc extends Document { - static getInitialProps({ req, renderPage }: NextDocumentContext) { + static async getInitialProps(ctx: NextDocumentContext) { + const { req, renderPage } = ctx; + // without callback const _page = renderPage(); @@ -43,7 +45,9 @@ class MyDoc extends Document { const enhancer: Enhancer = App => props => ; const { html, head, buildManifest } = renderPage(enhancer); - const styles = [ - - {body} + + + + {body} ) ); diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index 8661716e75..2e38f58c39 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-loadable 5.5 // Project: https://github.com/thejameskyle/react-loadable#readme -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Oden S. // Ian Ker-Seymer // Tomek Łaziuk diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts index eacc05209e..5049669e35 100644 --- a/types/react-native-fbsdk/index.d.ts +++ b/types/react-native-fbsdk/index.d.ts @@ -639,6 +639,12 @@ export namespace AppEventsLogger { */ function flush(): void; + /** + * Sets a custom user ID to associate with all app events. + * The userID is persisted until it is cleared by passing nil. + */ + function setUserID(userID: string | null): void; + /** * For iOS only, sets and sends device token to register the current application for push notifications. * @platform ios diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2b59454222..4b06119df2 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -4111,6 +4111,11 @@ export class FlatList extends React.Component> { * by taps on items or by navigation actions. */ recordInteraction: () => void; + + /** + * Displays the scroll indicators momentarily. + */ + flashScrollIndicators: () => void; } /** diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 1fcbe153e6..801565dc8d 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -332,6 +332,14 @@ InteractionManager.runAfterInteractions(() => { }).then(() => "done"); export class FlatListTest extends React.Component, {}> { + list: FlatList | null = null; + + componentDidMount(): void { + if (this.list) { + this.list.flashScrollIndicators(); + } + } + _renderItem = (rowData: any) => { return ( @@ -345,6 +353,7 @@ export class FlatListTest extends React.Component, {}> { render() { return ( (this.list = list)} data={[1, 2, 3, 4, 5]} renderItem={this._renderItem} ItemSeparatorComponent={this._renderSeparator} diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 08e4343e42..2d5146289f 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -6,6 +6,7 @@ // Nicolas Pirotte // Cameron Knight // Kaare Hoff Skovgaard +// Matt Krick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -131,14 +132,14 @@ export interface PageInfo { } export interface ConnectionData { edges?: ReadonlyArray; - pageInfo?: Partial; + pageInfo?: Partial | null; } export type RelayPaginationProp = RelayProp & { hasMore(): boolean; isLoading(): boolean; loadMore( pageSize: number, - callback: (error?: Error) => void, + callback?: ((error?: Error) => void) | null, options?: RefetchOptions ): RelayRuntimeTypes.Disposable | undefined | null; refetchConnection( diff --git a/types/react-simple-maps/index.d.ts b/types/react-simple-maps/index.d.ts index e76c4e3f0d..49e392035d 100644 --- a/types/react-simple-maps/index.d.ts +++ b/types/react-simple-maps/index.d.ts @@ -1,10 +1,12 @@ // Type definitions for react-simple-maps 0.12 // Project: https://github.com/zcreativelabs/react-simple-maps#readme // Definitions by: Novikov Mihail +// Andrej Mihajlov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; +import { GeoProjection } from 'd3-geo'; export type Point = [number, number]; @@ -19,17 +21,21 @@ export interface Line { }; } +export interface ProjectionConfig { + scale: number; + xOffset: number; + yOffset: number; + rotation: [number, number, number]; + precision: number; +} + +export type ProjectionFunction = (width: number, height: number, config: ProjectionConfig) => GeoProjection; + export interface ComposableMapProps { width?: number; height?: number; - projection?: string | (() => void); - projectionConfig?: { - scale?: number; - xOffset?: number; - yOffset?: number; - rotation?: number[]; - precision?: number; - }; + projection?: string | ProjectionFunction; + projectionConfig?: Partial; style?: React.CSSProperties; defs?: SVGDefsElement; className?: string; @@ -68,7 +74,7 @@ export interface ZoomableGroupProps { export interface GeographiesProps { disableOptimization?: boolean; geography?: string | { [key: string]: any } | string[]; - children?: (geographies: object[], projection: (point: Point) => void) => void; + children?: (geographies: object[], projection: GeoProjection) => void; } export interface GeographyProps { @@ -76,7 +82,7 @@ export interface GeographyProps { precision?: number; round?: boolean; geography?: object; - projection?: (point: Point) => void; + projection?: GeoProjection; tabable?: boolean; style?: { default?: React.CSSProperties; diff --git a/types/react-ultimate-pagination/index.d.ts b/types/react-ultimate-pagination/index.d.ts new file mode 100644 index 0000000000..2f7c26c210 --- /dev/null +++ b/types/react-ultimate-pagination/index.d.ts @@ -0,0 +1,130 @@ +// Type definitions for react-ultimate-pagination 1.2 +// Project: https://github.com/ultimate-pagination/react-ultimate-pagination +// Definitions by: Ben Lorantfy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +import * as React from "react"; + +export interface PaginationComponentProps { + /** + * Number of pages that user should navigate to when item is activated (for items with type `PAGE` it also can be used as a label in UI) + */ + value: number; + + /** + * Show if `currentPage` if the same as `value` of an item (can be used to highlight a current page or disable first, previous, next or last page links when user is already on first/last page) + */ + isActive: boolean; + + /** + * Show if button should be disabled + */ + isDisabled: boolean; + + /** + * Should be called when user interacted with a component and the current page should be changed to the page represented by item (no arguments should be used, can be used for all item types) + */ + onClick: () => void; +} + +export enum ITEM_TYPES { + PAGE = "PAGE", + ELLIPSIS = "ELLIPSIS", + FIRST_PAGE_LINK = "FIRST_PAGE_LINK", + PREVIOUS_PAGE_LINK = "PREVIOUS_PAGE_LINK", + NEXT_PAGE_LINK = "NEXT_PAGE_LINK", + LAST_PAGE_LINK = "LAST_PAGE_LINK", +} + +export interface ItemTypeToComponent { + /** + * A link to a page + */ + PAGE: React.ComponentType; + + /** + * An item that represents groups of pages that currently are not visible in paginator (can be used to navigate to the page in the group that is the nearest to the current page) + */ + ELLIPSIS: React.ComponentType; + + /** + * A link to the first page + */ + FIRST_PAGE_LINK: React.ComponentType; + + /** + * A link to the previous page + */ + PREVIOUS_PAGE_LINK: React.ComponentType; + + /** + * A link to the next page + */ + NEXT_PAGE_LINK: React.ComponentType; + + /** + * A link to the last page + */ + LAST_PAGE_LINK: React.ComponentType; +} + +export interface CreateUltimatePaginationOptions { + /** + * An object that is used as a map from the item type to the React.js component that will be used to render this item + */ + itemTypeToComponent: ItemTypeToComponent; + + /** + * A React.js component that will be used as a wrapper for pagination items + */ + WrapperComponent?: string|React.ComponentType; +} + +export interface UltimatePaginationProps { + /** + * Current page number + */ + currentPage: number; + + /** + * Total number of pages + */ + totalPages: number; + + /** + * Number of always visible pages at the beginning and end + */ + boundaryPagesRange?: number; + + /** + * Number of always visible pages before and after the current one + */ + siblingPagesRange?: number; + + /** + * Boolean flag to hide ellipsis + */ + hideEllipsis?: boolean; + + /** + * Boolean flag to hide previous and next page links + */ + hidePreviousAndNextPageLinks?: boolean; + + /** + * Boolean flag to hide first and last page links + */ + hideFirstAndLastPageLinks?: boolean; + + /** + * Callback that will be called with new page when it should be changed by user interaction + */ + onChange?: (newPage: number) => void; + + /** + * Boolean flag to disable all buttons in pagination + */ + disabled?: boolean; +} + +export function createUltimatePagination(options: CreateUltimatePaginationOptions): React.ComponentType; diff --git a/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx new file mode 100644 index 0000000000..8cebdcbf52 --- /dev/null +++ b/types/react-ultimate-pagination/react-ultimate-pagination-tests.tsx @@ -0,0 +1,93 @@ +import * as React from "react"; +import { + PaginationComponentProps, + createUltimatePagination, + ItemTypeToComponent, + ITEM_TYPES +} from "react-ultimate-pagination"; + +function Page(props: PaginationComponentProps) { + return ( + + ); +} + +function PageWithExtraProps(props: PaginationComponentProps & { color: "red" }) { + return ( + + ); +} + +function Ellipsis(props: PaginationComponentProps) { + return ; +} + +function FirstPageLink(props: PaginationComponentProps) { + return ; +} + +function PreviousPageLink(props: PaginationComponentProps) { + return ; +} + +function NextPageLink(props: PaginationComponentProps) { + return ; +} + +function LastPageLink(props: PaginationComponentProps) { + return ; +} + +function Wrapper(props: { children: React.ReactChildren }) { + return

{props.children}
; +} + +// ItemTypeToComponent using strings +const itemTypeToComponent: ItemTypeToComponent = { + PAGE: Page, + ELLIPSIS: Ellipsis, + FIRST_PAGE_LINK: FirstPageLink, + PREVIOUS_PAGE_LINK: PreviousPageLink, + NEXT_PAGE_LINK: NextPageLink, + LAST_PAGE_LINK: LastPageLink +}; + +// ItemTypeToComponent using enum +const itemTypeToComponent2: ItemTypeToComponent = { + [ITEM_TYPES.PAGE]: Page, + [ITEM_TYPES.ELLIPSIS]: Ellipsis, + [ITEM_TYPES.FIRST_PAGE_LINK]: FirstPageLink, + [ITEM_TYPES.PREVIOUS_PAGE_LINK]: PreviousPageLink, + [ITEM_TYPES.NEXT_PAGE_LINK]: NextPageLink, + [ITEM_TYPES.LAST_PAGE_LINK]: LastPageLink +}; + +// ItemTypeToComponent using Page with extra props +const itemTypeToComponent3: Partial = { + [ITEM_TYPES.PAGE]: PageWithExtraProps, +}; + +const UltimatePagination = createUltimatePagination({ itemTypeToComponent, WrapperComponent: Wrapper }); // $ExpectType ComponentType + +// With required props +; + +// With all props + {}} + siblingPagesRange={99} +/>; + +// With unspported prop +; // $ExpectError diff --git a/types/react-ultimate-pagination/tsconfig.json b/types/react-ultimate-pagination/tsconfig.json new file mode 100644 index 0000000000..748045849b --- /dev/null +++ b/types/react-ultimate-pagination/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-ultimate-pagination-tests.tsx" + ] +} diff --git a/types/react-ultimate-pagination/tslint.json b/types/react-ultimate-pagination/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-ultimate-pagination/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 52c6a63b80..a87874b9fd 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React 16.7 +// Type definitions for React 16.8 // Project: http://facebook.github.io/react/ // Definitions by: Asana // AssureSign @@ -18,8 +18,9 @@ // Olivier Pascal // Martin Hochel // Frank Li -// Jessica Franco +// Jessica Franco // Paul Sherman +// Sunil Pai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -869,15 +870,15 @@ declare namespace React { function useEffect(effect: EffectCallback, inputs?: InputIdentityList): void; // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref /** - * `useImperativeMethods` customizes the instance value that is exposed to parent components when using + * `useImperativeHandle` customizes the instance value that is exposed to parent components when using * `ref`. As always, imperative code using refs should be avoided in most cases. * - * `useImperativeMethods` should be used with `React.forwardRef`. + * `useImperativeHandle` should be used with `React.forwardRef`. * * @version experimental - * @see https://reactjs.org/docs/hooks-reference.html#useimperativemethods + * @see https://reactjs.org/docs/hooks-reference.html#useimperativehandle */ - function useImperativeMethods(ref: Ref|undefined, init: () => R, inputs?: InputIdentityList): void; + function useImperativeHandle(ref: Ref|undefined, init: () => R, inputs?: InputIdentityList): void; // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. /** diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 5239d3b522..5cb0c1512c 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -21,7 +21,7 @@ export const FancyButton = React.forwardRef((props: FancyButtonProps, ref: React const buttonRef = React.useRef(null); const [count, setCount] = React.useState(0); - React.useImperativeMethods(ref, () => ({ + React.useImperativeHandle(ref, () => ({ fancyClick() { buttonRef.current!; // $ExpectType HTMLButtonElement }, @@ -91,7 +91,7 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { const didLayout = React.useRef(false); const id = React.useMemo(() => Math.random(), []); - React.useImperativeMethods(ref, () => ({ id }), [id]); + React.useImperativeHandle(ref, () => ({ id }), [id]); // $ExpectError React.useImperativeMethods(ref, () => ({}), [id]); diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index f05d136f69..0536a600ee 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Rebass 0.3.8 +// Type definitions for Rebass 3.0 // Project: https://github.com/jxnblk/rebass -// Definitions by: rhysd +// Definitions by: rhysd // ryee-dev // jamesmckenzie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,32 +14,33 @@ export interface BaseProps extends React.ClassAttributes { } export interface SpaceProps extends BaseProps { - m?: number | string; - mt?: number | string; - mr?: number | string; - mb?: number | string; - ml?: number | string; - mx?: number | string; - my?: number | string; - p?: number | string; - pt?: number | string; - pr?: number | string; - pb?: number | string; - pl?: number | string; - px?: number | string; - py?: number | string; + m?: number | string | ReadonlyArray; + mt?: number | string | ReadonlyArray; + mr?: number | string | ReadonlyArray; + mb?: number | string | ReadonlyArray; + ml?: number | string | ReadonlyArray; + mx?: number | string | ReadonlyArray; + my?: number | string | ReadonlyArray; + p?: number | string | ReadonlyArray; + pt?: number | string | ReadonlyArray; + pr?: number | string | ReadonlyArray; + pb?: number | string | ReadonlyArray; + pl?: number | string | ReadonlyArray; + px?: number | string | ReadonlyArray; + py?: number | string | ReadonlyArray; } export interface BoxProps extends SpaceProps { className?: string; width?: number | string | ReadonlyArray; fontSize?: number | ReadonlyArray; - css?: Object; + css?: object; color?: string; bg?: string; } -type BoxClass = React.StatelessComponent; -export declare const Box: BoxClass; +// tslint:disable-next-line:strict-export-declare-modifiers +type BoxClass = React.FunctionComponent; +export const Box: BoxClass; export interface ButtonProps extends BoxProps { fontWeight?: string; @@ -48,8 +49,7 @@ export interface ButtonProps extends BoxProps { borderRadius?: number | string; variant?: string; } -type ButtonClass = React.StatelessComponent; -export declare const Button: ButtonClass; +export const Button: React.FunctionComponent; export interface CardProps extends BoxProps { border?: number | string; @@ -63,8 +63,7 @@ export interface CardProps extends BoxProps { opacity?: number; variant?: string; } -type CardClass = React.StatelessComponent; -export declare const Card: CardClass; +export const Card: React.FunctionComponent; export interface FlexProps extends BoxProps { alignItems?: string; @@ -72,8 +71,7 @@ export interface FlexProps extends BoxProps { flexDirection?: string; flexWrap?: string; } -type FlexClass = React.StatelessComponent; -export declare const Flex: FlexClass; +export const Flex: React.FunctionComponent; export interface ImageProps extends BoxProps { height?: number | string; @@ -81,14 +79,12 @@ export interface ImageProps extends BoxProps { src?: string; alt?: string; } -type ImageClass = React.StatelessComponent; -export declare const Image: ImageClass; +export const Image: React.FunctionComponent; export interface LinkProps extends BoxProps { href?: string; } -type LinkClass = React.StatelessComponent; -export declare const Link: LinkClass; +export const Link: React.FunctionComponent; export interface TextProps extends BoxProps { fontSize?: number | ReadonlyArray; @@ -99,9 +95,7 @@ export interface TextProps extends BoxProps { lineHeight?: number | string; letterSpacing?: number | string; } -type TextClass = React.StatelessComponent; -export declare const Text: TextClass; +export const Text: React.FunctionComponent; -export interface HeadingProps extends TextProps {} -type HeadingClass = React.StatelessComponent; -export declare const Heading: HeadingClass; +export type HeadingProps = TextProps; +export const Heading: React.FunctionComponent; diff --git a/types/rebass/rebass-tests.tsx b/types/rebass/rebass-tests.tsx index fb0eae1ed4..53735775ff 100644 --- a/types/rebass/rebass-tests.tsx +++ b/types/rebass/rebass-tests.tsx @@ -1,8 +1,8 @@ -import * as React from 'react' -import { Box, Flex, Text, Heading, Button, Link, Image, Card } from 'rebass' +import * as React from 'react'; +import { Box, Flex, Text, Heading, Button, Link, Image, Card } from 'rebass'; -const RebassTests = () => ( - +() => ( + Hi, I'm a heading. @@ -32,4 +32,4 @@ const RebassTests = () => ( -) +); diff --git a/types/rebass/tslint.json b/types/rebass/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/rebass/tslint.json +++ b/types/rebass/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" } diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 426e74d6ba..fc127e9251 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -12,6 +12,7 @@ // Harry Cruse // Andrew Palugniok // Robert Stigsson +// Kosaku Kurino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -451,12 +452,23 @@ export interface PieProps extends EventAttributes, Partial | React.ReactElement | boolean; label?: { offsetRadius: number; - } | React.ReactElement | ContentRenderer | boolean; + } | React.ReactElement | ContentRenderer | boolean; activeShape?: object | ContentRenderer | React.ReactElement; activeIndex?: number | number[]; blendStroke?: boolean; } +export interface PieLabelRenderProps extends PieProps { + name: string; + percent?: number; + stroke: string; + index?: number; + textAnchor: string; + x: number; + y: number; + [key: string]: any; +} + export class Pie extends React.Component { } // NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). diff --git a/types/reduce-reducers/index.d.ts b/types/reduce-reducers/index.d.ts index d4bde0bc8a..19499c452c 100644 --- a/types/reduce-reducers/index.d.ts +++ b/types/reduce-reducers/index.d.ts @@ -1,7 +1,81 @@ -// Type definitions for reduce-reducers 0.1 +// Type definitions for reduce-reducers 0.2 // Project: https://github.com/acdlite/reduce-reducers // Definitions by: Huy Nguyen +// Dalius Dobravolskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Reducer } from 'redux'; +export default function reduceReducer(r0: Reducer, s: S | null): Reducer; +export default function reduceReducer(r0: Reducer, r1: Reducer, s: S | null): Reducer; +export default function reduceReducer(r0: Reducer, r1: Reducer, r2: Reducer, s: S | null): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + r8: Reducer, + s: S | null, +): Reducer; +export default function reduceReducer( + r0: Reducer, + r1: Reducer, + r2: Reducer, + r3: Reducer, + r4: Reducer, + r5: Reducer, + r6: Reducer, + r7: Reducer, + r8: Reducer, + r9: Reducer, + s: S | null, +): Reducer; export default function reduceReducer(...reducers: Array>): Reducer; diff --git a/types/reduce-reducers/reduce-reducers-tests.ts b/types/reduce-reducers/reduce-reducers-tests.ts index f542fe834a..f4fdd8fff3 100644 --- a/types/reduce-reducers/reduce-reducers-tests.ts +++ b/types/reduce-reducers/reduce-reducers-tests.ts @@ -1,13 +1,188 @@ import { - Reducer, - Action, + Reducer, + Action, } from 'redux'; import reduceReducers from 'reduce-reducers'; interface TestStore { - a: number; - b: string; + a: number; + b: string; } const firstReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; const secondReducer: (state: TestStore, action: Action) => TestStore = (a, b) => a; const finalReducer: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer); +const finalReducerWithState: (state: TestStore, action: Action) => TestStore = reduceReducers(firstReducer, secondReducer, null); + +const initialState: TestStore = { + a: 1, + b: '2', +}; + +const finalReducerWithInitialState: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + initialState); + +const reducer02: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer03: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer04: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer05: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer06: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer07: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer08: (state: TestStore, action: Action) => TestStore = (a, b) => a; +const reducer09: (state: TestStore, action: Action) => TestStore = (a, b) => a; + +const finalReducerWithInitialState02: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + initialState); +const finalReducerWithInitialState02null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + null); + +const finalReducerWithInitialState03: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + initialState); +const finalReducerWithInitialState03null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + null); + +const finalReducerWithInitialState04: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + initialState); +const finalReducerWithInitialState04null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + null); + +const finalReducerWithInitialState05: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + initialState); +const finalReducerWithInitialState05null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + null); + +const finalReducerWithInitialState06: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + initialState); +const finalReducerWithInitialState06null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + null); + +const finalReducerWithInitialState07: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + initialState); +const finalReducerWithInitialState07null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + null); + +const finalReducerWithInitialState08: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + initialState); +const finalReducerWithInitialState08null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + null); + +const finalReducerWithoutInitialState09: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09); +const finalReducerWithInitialState09: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09, + initialState); +const finalReducerWithInitialState09null: (state: TestStore, action: Action) => TestStore = reduceReducers( + firstReducer, + secondReducer, + reducer02, + reducer03, + reducer04, + reducer05, + reducer06, + reducer07, + reducer08, + reducer09, + null); diff --git a/types/redux-state-sync/index.d.ts b/types/redux-state-sync/index.d.ts new file mode 100644 index 0000000000..fb7e0f84b5 --- /dev/null +++ b/types/redux-state-sync/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for redux-state-sync 2.0 +// Project: https://github.com/AOHUA/redux-state-sync#readme +// Definitions by: MU AOHUA +// AntonioMendez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Store, Reducer, Middleware, AnyAction } from "redux"; +import BroadcastChannel from "broadcast-channel"; + +export interface Stamp { + $uuid: string; + $wuid: string; +} +export type StampedAction = Stamp & AnyAction; + +export interface Config { + channel?: string; + predicate?: (type?: string) => boolean | null; + blacklist?: string[]; + whitelist?: string[]; + broadcastChannelOption?: object | null; +} + +export interface MessageListenerConfig { + channel: BroadcastChannel; + dispatch: (action: AnyAction | StampedAction) => void; + allowed: (type?: string) => boolean; +} + +export function generateUuidForAction(action: AnyAction): StampedAction; +export function isActionAllowed(config: Config): (type: string) => boolean; +export function createMessageListener(config: MessageListenerConfig): void; +export function createStateSyncMiddleware(config?: Config): Middleware; +export function withReduxStateSync( + appReducer: Reducer +): (state: any, action: AnyAction) => Reducer; +export function initStateWithPrevTab(store: Store): Store; diff --git a/types/redux-state-sync/package.json b/types/redux-state-sync/package.json new file mode 100644 index 0000000000..d39f9e8fc6 --- /dev/null +++ b/types/redux-state-sync/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "broadcast-channel": "^2.1.8", + "redux": "^4.0.1" + } +} diff --git a/types/redux-state-sync/redux-state-sync-tests.ts b/types/redux-state-sync/redux-state-sync-tests.ts new file mode 100644 index 0000000000..3f5e689675 --- /dev/null +++ b/types/redux-state-sync/redux-state-sync-tests.ts @@ -0,0 +1,22 @@ +import { createStore, applyMiddleware, Action } from "redux"; +import { createStateSyncMiddleware, initStateWithPrevTab, withReduxStateSync } from "redux-state-sync"; + +interface TestState { + a: number; + b: string; + c: string; +} +const middleware = createStateSyncMiddleware({ + channel: 'test', + predicate: (type) => true, + blacklist: [], + whitelist: [], + broadcastChannelOption: {} + }); + +function rootReducer(state: TestState, action: Action): TestState { + return state; +} + +const store = createStore(withReduxStateSync(rootReducer), ['test'], applyMiddleware(middleware)); +initStateWithPrevTab(store); diff --git a/types/redux-state-sync/tsconfig.json b/types/redux-state-sync/tsconfig.json new file mode 100644 index 0000000000..dd15d9a067 --- /dev/null +++ b/types/redux-state-sync/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-state-sync-tests.ts" + ] +} diff --git a/types/redux-state-sync/tslint.json b/types/redux-state-sync/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/redux-state-sync/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 27ae20706c..a4b7106c4f 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -23,6 +23,7 @@ export type RelayMutationRequest = any; export type RelayQueryRequest = any; export type ConcreteFragmentDefinition = object; export type ConcreteOperationDefinition = object; +export type ReaderFragment = object; /** * FIXME: RelayContainer used to be typed with ReactClass, but @@ -41,9 +42,40 @@ export type RelayContainer = any; // ~~~~~~~~~~~~~~~~~~~~~ // File: https://github.com/facebook/relay/blob/fe0e70f10bbcba1fff89911313ea69f24569464b/packages/relay-runtime/util/RelayConcreteNode.js -export type ConcreteFragment = any; -export type ConcreteRequest = any; -export type ConcreteBatchRequest = any; +export interface ConcreteFragment { + kind: string; + name: string; + type: string; + metadata: {[key: string]: any} | null; + argumentDefinitions: any[]; + selections: any[]; +} +export interface ConcreteRequest { + kind: string; + operationKind: string; + name: string; + id: string | null; + text: string | null; + metadata: {[key: string]: any}; + fragment: ConcreteFragment; + operation: any; +} +export interface ConcreteBatchRequest { + kind: string; + operationKind: string; + name: string; + metadata: {[key: string]: any}; + fragment: ConcreteFragment; + requests: Array<{ + name: string; + id: string | null; + text: string | null; + argumentDependencies: any[] | null; + operation: any; + }>; +} + +export function getRequest(taggedNode: GraphQLTaggedNode): ConcreteRequest; export type RequestNode = ConcreteRequest | ConcreteBatchRequest; diff --git a/types/responselike/index.d.ts b/types/responselike/index.d.ts new file mode 100644 index 0000000000..7152388232 --- /dev/null +++ b/types/responselike/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for responselike 1.0 +// Project: https://github.com/lukechilds/responselike#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { IncomingMessage } from 'http'; +import { Stream } from 'stream'; + +export = ResponseLike; + +/** + * Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + */ +declare class ResponseLike extends Stream.Readable { + statusCode: number; + headers: { [header: string]: string | string[] | undefined }; + body: Buffer; + url: string; + + /** + * @param statusCode HTTP response status code. + * @param headers HTTP headers object. Keys will be automatically lowercased. + * @param body A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + * @param url Request URL string. + */ + constructor( + statusCode: number, + headers: { [header: string]: string | string[] | undefined }, + body: Buffer, + url: string + ); +} diff --git a/types/responselike/responselike-tests.ts b/types/responselike/responselike-tests.ts new file mode 100644 index 0000000000..95c5e4f701 --- /dev/null +++ b/types/responselike/responselike-tests.ts @@ -0,0 +1,10 @@ +import Response = require('responselike'); + +const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); + +response.statusCode; // $ExpectType number +response.headers; // $ExpectType { [header: string]: string | string[] | undefined; } +response.body; // $ExpectType Buffer +response.url; // $ExpectType string + +response.pipe(process.stdout); diff --git a/types/responselike/tsconfig.json b/types/responselike/tsconfig.json new file mode 100644 index 0000000000..2c0a9e392b --- /dev/null +++ b/types/responselike/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", + "responselike-tests.ts" + ] +} diff --git a/types/responselike/tslint.json b/types/responselike/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/responselike/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rollup-plugin-delete/index.d.ts b/types/rollup-plugin-delete/index.d.ts new file mode 100644 index 0000000000..9f9cfe020d --- /dev/null +++ b/types/rollup-plugin-delete/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for rollup-plugin-delete 0.2 +// Project: https://github.com/vladshcherbin/rollup-plugin-delete#readme +// Definitions by: Vlad Shcherbin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import del = require('del'); +import { Plugin } from 'rollup'; + +export interface Options extends del.Options { + /** + * Patterns of files and folders to be deleted. + * @default [] + */ + readonly targets: ReadonlyArray | string; + + /** + * Outputs removed files and folders to console. + * @default false + */ + readonly verbose?: boolean; +} + +export default function(options?: Options): Plugin; diff --git a/types/rollup-plugin-delete/package.json b/types/rollup-plugin-delete/package.json new file mode 100644 index 0000000000..272f65edde --- /dev/null +++ b/types/rollup-plugin-delete/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": ">=0.60.0" + } +} diff --git a/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts b/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts new file mode 100644 index 0000000000..eff3508e29 --- /dev/null +++ b/types/rollup-plugin-delete/rollup-plugin-delete-tests.ts @@ -0,0 +1,13 @@ +import del from 'rollup-plugin-delete'; + +del(); // $ExpectType Plugin + +del({}); // $ExpectError + +del({ targets: '/dist' }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true, dryRun: true }); // $ExpectType Plugin + +del({ targets: ['/dist'], verbose: true, dryRun: true, debug: true }); // $ExpectType Plugin diff --git a/types/rollup-plugin-delete/tsconfig.json b/types/rollup-plugin-delete/tsconfig.json new file mode 100644 index 0000000000..d03999e03a --- /dev/null +++ b/types/rollup-plugin-delete/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", + "rollup-plugin-delete-tests.ts" + ] +} diff --git a/types/rollup-plugin-delete/tslint.json b/types/rollup-plugin-delete/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-delete/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rollup-plugin-node-builtins/index.d.ts b/types/rollup-plugin-node-builtins/index.d.ts new file mode 100644 index 0000000000..e839485ac9 --- /dev/null +++ b/types/rollup-plugin-node-builtins/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for rollup-plugin-node-builtins 2.1 +// Project: https://github.com/calvinmetcalf/rollup-plugin-node-builtins#readme +// Definitions by: Hugo Alliaume +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Plugin } from 'rollup'; + +export interface Options { + crypto?: boolean; + fs?: boolean; +} + +export default function builtins(options?: Options): Plugin; diff --git a/types/rollup-plugin-node-builtins/package.json b/types/rollup-plugin-node-builtins/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-node-builtins/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts b/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts new file mode 100644 index 0000000000..53e488cd00 --- /dev/null +++ b/types/rollup-plugin-node-builtins/rollup-plugin-node-builtins-tests.ts @@ -0,0 +1,16 @@ +import builtins from 'rollup-plugin-node-builtins'; + +// No options (default) +(() => { + // $ExpectType Plugin + builtins(); +})(); + +// With `crypto` and `fs` enabled +(() => { + // $ExpectType Plugin + builtins({ + crypto: true, + fs: true, + }); +})(); diff --git a/types/rollup-plugin-node-builtins/tsconfig.json b/types/rollup-plugin-node-builtins/tsconfig.json new file mode 100644 index 0000000000..c0a6e1e787 --- /dev/null +++ b/types/rollup-plugin-node-builtins/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", + "rollup-plugin-node-builtins-tests.ts" + ] +} diff --git a/types/rollup-plugin-node-builtins/tslint.json b/types/rollup-plugin-node-builtins/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-node-builtins/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rollup-plugin-node-globals/index.d.ts b/types/rollup-plugin-node-globals/index.d.ts new file mode 100644 index 0000000000..2cf29ae912 --- /dev/null +++ b/types/rollup-plugin-node-globals/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for rollup-plugin-node-globals 1.4 +// Project: https://github.com/calvinmetcalf/rollup-plugin-node-globals#readme +// Definitions by: Hugo Alliaume +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Plugin } from 'rollup'; + +export interface Options { + // Every files will be parsed by default, but you can specify which files to include or exclude + include?: Array | string | RegExp | null; + exclude?: Array | string | RegExp | null; + + // Enable sourcemaps support + sourceMap ?: boolean; + + // Plugin's options + process?: boolean; + global?: boolean; + buffer?: boolean; + dirname?: boolean; + filename?: boolean; + baseDir?: string; +} + +export default function globals(options?: Options): Plugin; diff --git a/types/rollup-plugin-node-globals/package.json b/types/rollup-plugin-node-globals/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-node-globals/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts b/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts new file mode 100644 index 0000000000..93d10a2730 --- /dev/null +++ b/types/rollup-plugin-node-globals/rollup-plugin-node-globals-tests.ts @@ -0,0 +1,43 @@ +import globals from 'rollup-plugin-node-globals'; + +// No options (default) +(() => { + // $ExpectType Plugin + globals(); +})(); + +// With every options +(() => { + // $ExpectType Plugin + globals({ + process: false, + global: false, + buffer: false, + dirname: false, + filename: false, + baseDir: '/', + }); +})(); + +// Filter files +(() => { + // $ExpectType Plugin + globals({ + include: '*.js', + exclude: '*.js', + }); + + // $ExpectType Plugin + globals({ + include: /.js$/, + exclude: ['foo.js', 'bar.js'], + }); +})(); + +// Sourcemaps +(() => { + // $ExpectType Plugin + globals({ + sourceMap: false, + }); +})(); diff --git a/types/rollup-plugin-node-globals/tsconfig.json b/types/rollup-plugin-node-globals/tsconfig.json new file mode 100644 index 0000000000..29e93758c9 --- /dev/null +++ b/types/rollup-plugin-node-globals/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", + "rollup-plugin-node-globals-tests.ts" + ] +} diff --git a/types/rollup-plugin-node-globals/tslint.json b/types/rollup-plugin-node-globals/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-node-globals/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/script-ext-html-webpack-plugin/index.d.ts b/types/script-ext-html-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..636ac550e5 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for script-ext-html-webpack-plugin 2.1 +// Project: https://github.com/numical/script-ext-html-webpack-plugin +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from "webpack"; + +export = ScriptExtHtmlWebpackPlugin; + +declare class ScriptExtHtmlWebpackPlugin extends Plugin { + constructor(options?: ScriptExtHtmlWebpackPlugin.Options); +} + +type ScriptMatchingPatternBase = + | string + | RegExp + | ReadonlyArray; + +interface ScriptMatchingPatternHash { + test: ScriptMatchingPatternBase; +} + +type ScriptMatchingPattern = + | ScriptMatchingPatternBase + | ScriptMatchingPatternHash; + +type ScriptMatchingPatternPre = + | ScriptMatchingPatternBase + | ScriptMatchingPatternHash & { + chunks?: "initial" | "async" | "all"; + }; + +interface Custom { + test: ScriptMatchingPattern; + attribute: string; + value?: string; +} + +declare namespace ScriptExtHtmlWebpackPlugin { + interface Options { + /** + * scripts that should be inlined in the html (default: `[]`) + */ + inline?: ScriptMatchingPattern; + /** + * script names that should have no attribute (default: `[]`) + */ + sync?: ScriptMatchingPattern; + /** + * script names that should have an async attribute (default: `[]`) + */ + async?: ScriptMatchingPattern; + /** + * script names that should have a defer attribute (default: `[]`) + */ + defer?: ScriptMatchingPattern; + /** + * the default attribute to set - 'sync' actually results in no attribute (default: 'sync') + */ + defaultAttribute?: "sync" | "async" | "defer"; + /** + * script names that should have a type="module" attribute (default: `[]`) + */ + module?: ScriptMatchingPattern; + /** + * scripts that should have accompanying preload resource hints (default: `[]`) + */ + preload?: ScriptMatchingPatternPre; + /** + * scripts that should have accompanying prefetch resource hints (default: `[]`) + */ + prefetch?: ScriptMatchingPatternPre; + /** + * scripts that should have a custom attribute(s) added, the attribute(s), and the value(s) + */ + custom?: Custom | Custom[]; + } +} diff --git a/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts b/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts new file mode 100644 index 0000000000..84c42b2ae9 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/script-ext-html-webpack-plugin-tests.ts @@ -0,0 +1,112 @@ +import ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin"); + +new ScriptExtHtmlWebpackPlugin(); +new ScriptExtHtmlWebpackPlugin({}); + +new ScriptExtHtmlWebpackPlugin({ + inline: "string", + sync: "string", + async: "string", + defer: "string", + module: "string", + preload: "string", + prefetch: "string" +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: ["array"], + sync: ["array"], + async: ["array"], + defer: ["array"], + module: ["array"], + preload: ["array"], + prefetch: ["array"] +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: /regexp/, + sync: /regexp/, + async: /regexp/, + defer: /regexp/, + module: /regexp/, + preload: /regexp/, + prefetch: /regexp/ +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: "string" }, + sync: { test: "string" }, + async: { test: "string" }, + defer: { test: "string" }, + module: { test: "string" }, + preload: { test: "string" }, + prefetch: { test: "string" } +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: ["array"] }, + sync: { test: ["array"] }, + async: { test: ["array"] }, + defer: { test: ["array"] }, + module: { test: ["array"] }, + preload: { test: ["array"] }, + prefetch: { test: ["array"] } +}); + +new ScriptExtHtmlWebpackPlugin({ + inline: { test: /regexp/ }, + sync: { test: /regexp/ }, + async: { test: /regexp/ }, + defer: { test: /regexp/ }, + module: { test: /regexp/ }, + preload: { test: /regexp/ }, + prefetch: { test: /regexp/ } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "initial" }, + prefetch: { test: "string", chunks: "initial" } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "async" }, + prefetch: { test: "string", chunks: "async" } +}); + +new ScriptExtHtmlWebpackPlugin({ + preload: { test: "string", chunks: "all" }, + prefetch: { test: "string", chunks: "all" } +}); + +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "sync" }); +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "async" }); +new ScriptExtHtmlWebpackPlugin({ defaultAttribute: "defer" }); + +new ScriptExtHtmlWebpackPlugin({ + custom: { + test: "string", + attribute: "string" + } +}); + +new ScriptExtHtmlWebpackPlugin({ + custom: { + test: ["array"], + attribute: "string", + value: "string" + } +}); + +new ScriptExtHtmlWebpackPlugin({ + custom: [ + { + test: /regexp/, + attribute: "string" + }, + { + test: "string", + attribute: "string", + value: "string" + } + ] +}); diff --git a/types/script-ext-html-webpack-plugin/tsconfig.json b/types/script-ext-html-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..32c8e618e3 --- /dev/null +++ b/types/script-ext-html-webpack-plugin/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", "script-ext-html-webpack-plugin-tests.ts"] +} diff --git a/types/script-ext-html-webpack-plugin/tslint.json b/types/script-ext-html-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/script-ext-html-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 3c8fc11155..f4a0c01efb 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 - /// interface Select2QueryOptions { @@ -23,8 +22,8 @@ interface AjaxFunction { interface Select2AjaxOptions extends JQueryAjaxSettings { transport?: AjaxFunction; /** - * Url to make request to, Can be string or a function returning a string. - */ + * Url to make request to, Can be string or a function returning a string. + */ url?: any; dataType?: string; quietMillis?: number; @@ -93,77 +92,77 @@ interface Select2Plugin { (): JQuery; (it: IdTextPair): JQuery; - /** - * Get the id value of the current selection - */ + /** + * Get the id value of the current selection + */ (method: 'val'): any; - /** - * Set the id value of the current selection - * @params value Value to set the id to - * @params triggerChange Should a change event be triggered - */ + /** + * Set the id value of the current selection + * @params value Value to set the id to + * @params triggerChange Should a change event be triggered + */ (method: 'val', value: any, triggerChange?: boolean): any; - /** - * Get the data object of the current selection - */ + /** + * Get the data object of the current selection + */ (method: 'data'): any; - /** - * Set the data of the current selection - * @params value Object to set the data to - * @params triggerChange Should a change event be triggered - */ + /** + * Set the data of the current selection + * @params value Object to set the data to + * @params triggerChange Should a change event be triggered + */ (method: 'data', value: any, triggerChange?: boolean): any; - /** - * Whether it is open - */ + /** + * Whether it is open + */ (method: 'opened'): boolean; - /** - * Whether it is in focus - */ + /** + * Whether it is in focus + */ (method: 'isFocused'): boolean; - /** - * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. - */ + /** + * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. + */ (method: 'destroy'): JQuery; - /** - * Opens the dropdown - */ + /** + * Opens the dropdown + */ (method: 'open'): JQuery; - /** - * Closes the dropdown - */ + /** + * Closes the dropdown + */ (method: 'close'): JQuery; - /** - * Disables Select2 - */ + /** + * Disables Select2 + */ (method: 'disable'): JQuery; - /** - * Enables or disables Select2 and its underlying form component - * @param value True if it should be enabled false if it should be disabled - */ + /** + * Enables or disables Select2 and its underlying form component + * @param value True if it should be enabled false if it should be disabled + */ (method: 'enable', value?: boolean): JQuery; - /** - * Enable its focus - */ + /** + * Enable its focus + */ (method: 'focus'): JQuery; - /** - * Toggles readonly mode on Select2 and its underlying form component - * @param value True if it should be readonly false if it should be read write - */ + /** + * Toggles readonly mode on Select2 and its underlying form component + * @param value True if it should be readonly false if it should be read write + */ (method: 'readonly', value: boolean): JQuery; - /** - * Retrieves the main container element that wraps all of DOM added by Select2 - */ + /** + * Retrieves the main container element that wraps all of DOM added by Select2 + */ (method: 'container'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has started - */ + /** + * Notifies Select2 that a drag and drop sorting operation has started + */ (method: 'onSortStart'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has finished - */ + /** + * Notifies Select2 that a drag and drop sorting operation has finished + */ (method: 'onSortEnd'): JQuery; - /** + /** * Executes a new search using the provided value. Example: $("#tags").select2("search", "California") */ (method: 'search'): JQuery; diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index fe7f900e3d..4a0a496e13 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -9,9 +9,9 @@ $("#e2_2").select2({ $("#e3").select2({ minimumInputLength: 2 }); -function format(state) { +function format(state: any) { if (!state.id) return state.text; - return "" + state.text; + return `${state.text}`; } $("#e4").select2({ formatResult: format, @@ -21,10 +21,10 @@ $("#e5").select2({ minimumInputLength: 1, query: function (query) { console.info('current element value:', query.element.val()); - var data = { results: [] }, i, j, s; - for (i = 1; i < 5; i++) { - s = ""; - for (j = 0; j < i; j++) { s = s + query.term; } + const data = { results: [] as IdTextPair[] }; + for (let i = 1; i < 5; i++) { + let s = ""; + for (let j = 0; j < i; j++) { s = s + query.term; } data.results.push({ id: query.term + i, text: s }); } } @@ -35,7 +35,7 @@ $("#e10").select2({ data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] }); -var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; +const data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; $("#e10_2").select2({ data: { results: data, text: 'tag' }, @@ -44,11 +44,20 @@ $("#e10_2").select2({ }); $("#e10_3").select2({ - data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, + data: { + results: data, + text: (item: {tag: string}) => { + console.log('called with', item); + return item.tag; + } + }, formatSelection: format, formatResult: format }); -var movieFormatResult, movieFormatSelection; + +let movieFormatResult; +let movieFormatSelection; + $("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, @@ -75,7 +84,7 @@ $("#e6").select2({ placeholder: "Search for a movie", minimumInputLength: 1, ajax: { - url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, + url: () => "http://api.rottentomatoes.com/api/public/v1.0/movies.json", dataType: 'jsonp', data: function (term, page) { return { @@ -131,7 +140,7 @@ $("#e7").select2({ }; }, results: function (data, page) { - var more = (page * 10) < data.total; + const more = (page * 10) < data.total; return { results: data.movies, more: more }; } }, @@ -140,7 +149,7 @@ $("#e7").select2({ dropdownCssClass: "bigdrop" }); -function sort(elements) { +function sort(elements: any) { return elements.sort(); } @@ -170,13 +179,12 @@ $("#e11_2").select2({ multiple: true, data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] }); -function log(e) { - var item = $("
  • " + e + "
  • "); +function log(e: string) { + const item = $(`
  • ${e}
  • `); $("#events_11").append(item); item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); } $("#e11") - // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) .on("open", function () { log("open"); }); $("#e11_2") @@ -201,7 +209,7 @@ $("#e16_2").select2(); $("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); $("#e16_disable").click(function () { $("#e16,#e16_2").select2("enable", false); }); $("#e17").select2({ - matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } + matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) === 0; } }); $("#e17_2").select2({ matcher: function (term, text, opt) { @@ -210,22 +218,26 @@ $("#e17_2").select2({ } }); $("#e18,#e18_2").select2(); -alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); -$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { - return currentSearchTerm; -}}); +alert("Selected value is: " + $("#e8").select2("val")); +$("#e8").select2("val", {id: "CA", text: "Califoria"}); -$('#e20').select2({ - tokenizer: (textInput, selection, selectCallback, options) => { - if (options.dropdownAutoWidth) { - selectCallback(); - return null; - } else if (options.allowClear) { - selectCallback(textInput + '_'); - return textInput + '_'; +$("#e1").select2({ + nextSearchTerm: (selectedObject: object, currentSearchTerm: string) => { + return currentSearchTerm; + } +}); + +$("#id").select2({ + tokenizer: (textInput, selection, selectCallback, options) => { + if (options.dropdownAutoWidth) { + selectCallback(); + return null; + } else if (options.allowClear) { + selectCallback(textInput + '_'); + return textInput + '_'; + } + selection.push('extra'); } - selection.push('extra'); - } }); $("#e8").select2("val"); diff --git a/types/select2/v3/tsconfig.json b/types/select2/v3/tsconfig.json index 8b8f30ed05..aeb9f31a86 100644 --- a/types/select2/v3/tsconfig.json +++ b/types/select2/v3/tsconfig.json @@ -5,8 +5,8 @@ "es6", "dom" ], - "noImplicitAny": false, - "noImplicitThis": false, + "noImplicitAny": true, + "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../../", diff --git a/types/select2/v3/tslint.json b/types/select2/v3/tslint.json index a41bf5d19a..fdbd83d321 100644 --- a/types/select2/v3/tslint.json +++ b/types/select2/v3/tslint.json @@ -1,79 +1,9 @@ { "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 + "unified-signatures": false } } diff --git a/types/semantic-release/index.d.ts b/types/semantic-release/index.d.ts new file mode 100644 index 0000000000..656461b756 --- /dev/null +++ b/types/semantic-release/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for semantic-release 15.13 +// Project: https://github.com/semantic-release/semantic-release#readme +// Definitions by: Leonardo Gatica +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * The semantic release configuration itself. + */ +export interface GlobalConfig { + /** The full prepare step configuration. */ + prepare?: any; + /** The branch on which releases should happen. */ + branch: string; + /** The Git repository URL, in any supported format. */ + repositoryUrl: string; + /** The Git tag format used by semantic-release to identify releases. */ + tagFormat: string; +} + +export interface LastRelease { + /** The version name of the release */ + version: string; + /** The Git tag of the release. */ + gitTag: string; + /** The Git checksum of the last commit of the release. */ + gitHead: string; +} + +export interface NextRelease extends LastRelease { + /** The release notes of the next release. */ + notes: string; +} + +export interface Context { + /** The semantic release configuration itself. */ + options?: GlobalConfig; + /** The previous release details. */ + lastRelease?: LastRelease; + /** The next release details. */ + nextRelease?: NextRelease; + /** The shared logger instance of semantic release. */ + logger: { + log: (message: string, ...vars: any[]) => void, + error: (message: string, ...vars: any[]) => void, + }; +} diff --git a/types/semantic-release/semantic-release-tests.ts b/types/semantic-release/semantic-release-tests.ts new file mode 100644 index 0000000000..0c954fe295 --- /dev/null +++ b/types/semantic-release/semantic-release-tests.ts @@ -0,0 +1,17 @@ +import * as lib from 'semantic-release'; + +function publish(pluginConfig: any, context: lib.Context) { + const version = context.nextRelease && context.nextRelease.version; + context.logger.log(`New version ${version}`); +} + +const context = { + nextRelease: { + version: '1.0.0', + gitTag: '1.0.0', + gitHead: 'f1eed296d2ffe184fb15f52b1c5ad778f5c87645', + notes: 'New release' + }, + logger: console +}; +publish({}, context); diff --git a/types/semantic-release/tsconfig.json b/types/semantic-release/tsconfig.json new file mode 100644 index 0000000000..d226e296ce --- /dev/null +++ b/types/semantic-release/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "semantic-release-tests.ts" + ] +} diff --git a/types/semantic-release/tslint.json b/types/semantic-release/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/semantic-release/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/set-cookie-parser/index.d.ts b/types/set-cookie-parser/index.d.ts index ea00ab4399..3da321ddb0 100644 --- a/types/set-cookie-parser/index.d.ts +++ b/types/set-cookie-parser/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for set-cookie-parser // Project: https://github.com/nfriedly/set-cookie-parser // Definitions by: Nick Paddock +// Ilya Zaytsev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,10 +9,10 @@ declare module "set-cookie-parser" { import http = require("http"); - function SetCookieParser(input: string | ReadonlyArray | http.IncomingMessage): SetCookieParser.Cookie[]; + function SetCookieParser(input: string | ReadonlyArray | http.IncomingMessage, options?: SetCookieParser.Options): SetCookieParser.Cookie[]; namespace SetCookieParser { - function parse(input: string | ReadonlyArray | http.IncomingMessage): Cookie[]; + function parse(input: string | ReadonlyArray | http.IncomingMessage, options?: Options): Cookie[]; function splitCookiesString(input: string | ReadonlyArray | void): string[]; @@ -25,6 +26,11 @@ declare module "set-cookie-parser" { secure?: boolean; httpOnly?: boolean; } + + type Options = { + decodeValues?: boolean; + map?: boolean; + } } export = SetCookieParser; diff --git a/types/set-cookie-parser/set-cookie-parser-tests.ts b/types/set-cookie-parser/set-cookie-parser-tests.ts index ab4e88005d..578e257f0c 100644 --- a/types/set-cookie-parser/set-cookie-parser-tests.ts +++ b/types/set-cookie-parser/set-cookie-parser-tests.ts @@ -88,3 +88,22 @@ assert.deepStrictEqual(cookiesString, [ 'foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure', 'baz=buz; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure', ]) + +// Use decodeValues=false option +var notDecodedValueCookies = setCookie.parse('user=%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 3000 10:01:11 GMT; HttpOnly; Secure', { decodeValues: false }); +assert.equal(notDecodedValueCookies[0].value, '%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2'); + +var decodedValueCookies = setCookie.parse('user=%D0%98%D0%BB%D1%8C%D1%8F%20%D0%97%D0%B0%D0%B9%D1%86%D0%B5%D0%B2; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 3000 10:01:11 GMT; HttpOnly; Secure', { decodeValues: true }); +assert.equal(decodedValueCookies[0].value, 'Илья Зайцев'); + +// Use map=true option +var expectedCookiesMap = { + foo: { + name: 'foo', + value: 'bar', + maxAge: 1000, + domain: '.example.com', + } +}; +var cookiesMap = setCookie.parse('foo=bar; Max-Age=1000; Domain=.example.com;', { map: true }); +assert.deepStrictEqual(cookiesMap, expectedCookiesMap); \ No newline at end of file diff --git a/types/snoowrap/dist/objects/LiveThread.d.ts b/types/snoowrap/dist/objects/LiveThread.d.ts index ba34886fbb..594fc50247 100644 --- a/types/snoowrap/dist/objects/LiveThread.d.ts +++ b/types/snoowrap/dist/objects/LiveThread.d.ts @@ -26,8 +26,8 @@ export default class LiveThread extends RedditContent { deleteUpdate(options: { id: string; }): Promise; editSettings(options: LiveThreadSettings): Promise; getContributors(): Promise; - getDiscussions(options?: ListingOptions): Listing; - getRecentUpdates(options?: ListingOptions): Listing; + getDiscussions(options?: ListingOptions): Promise>; + getRecentUpdates(options?: ListingOptions): Promise>; inviteContributor(options: { name: string; permissions: Permissions[]}): Promise; leaveContributor(): Promise; removeContributor(options: { name: string; }): Promise; diff --git a/types/snoowrap/dist/objects/RedditUser.d.ts b/types/snoowrap/dist/objects/RedditUser.d.ts index a93cac98cd..35bc56eb9e 100644 --- a/types/snoowrap/dist/objects/RedditUser.d.ts +++ b/types/snoowrap/dist/objects/RedditUser.d.ts @@ -100,18 +100,18 @@ export default class RedditUser extends RedditContent { assignFlair(options: any): Promise; friend(options: any): Promise; - getComments(options?: any): Listing; - getDownvotedContent(options?: any): Listing; + getComments(options?: any): Promise>; + getDownvotedContent(options?: any): Promise>; getFriendInformation(): Promise; - getGildedContent(options?: any): Listing; - getHiddenContent(options?: any): Listing; + getGildedContent(options?: any): Promise>; + getHiddenContent(options?: any): Promise>; getMultireddit(name: string): MultiReddit; getMultireddits(): Promise; - getOverview(options?: any): Listing; - getSavedContent(options?: any): Listing; - getSubmissions(options?: any): Listing; + getOverview(options?: any): Promise>; + getSavedContent(options?: any): Promise>; + getSubmissions(options?: any): Promise>; getTrophies(): Promise; - getUpvotedContent(options?: any): Listing; + getUpvotedContent(options?: any): Promise>; giveGold(months: string): Promise; unfriend(): Promise; } diff --git a/types/snoowrap/dist/objects/Submission.d.ts b/types/snoowrap/dist/objects/Submission.d.ts index e2e7dc78d1..5986ac59cc 100644 --- a/types/snoowrap/dist/objects/Submission.d.ts +++ b/types/snoowrap/dist/objects/Submission.d.ts @@ -1,8 +1,7 @@ import { Sort } from '../..'; import Comment from './Comment'; import Listing, { ListingOptions } from './Listing'; -import RedditUser from './RedditUser'; -import Subreddit, { FlairTemplate } from './Subreddit'; +import { FlairTemplate } from './Subreddit'; import VoteableContent, { RichTextFlair } from './VoteableContent'; interface Media { @@ -113,7 +112,7 @@ export default class Submission extends VoteableContent { assignFlair(options: { text: string; cssClass: string; }): Promise; disableContestMode(): Promise; enableContestMode(): Promise; - getDuplicates(options?: ListingOptions): Listing; + getDuplicates(options?: ListingOptions): Promise>; getLinkFlairTemplates(): Promise; /* @deprecated */ getRelated(options?: ListingOptions): Submission; hide(): Promise; diff --git a/types/snoowrap/dist/objects/Subreddit.d.ts b/types/snoowrap/dist/objects/Subreddit.d.ts index 67623a17af..a9de52632d 100644 --- a/types/snoowrap/dist/objects/Subreddit.d.ts +++ b/types/snoowrap/dist/objects/Subreddit.d.ts @@ -1,12 +1,12 @@ -import { Sort, ModAction, SubmitSelfPostOptions, SubmitLinkOptions, BaseSearchOptions } from '../..'; +import { BaseSearchOptions, ModAction, Sort, SubmitLinkOptions, SubmitSelfPostOptions } from '../..'; import Comment from './Comment'; import Listing, { ListingOptions } from './Listing'; import PrivateMessage from './PrivateMessage'; import RedditContent from './RedditContent'; import RedditUser from './RedditUser'; import Submission from './Submission'; -import WikiPage, { WikiPageRevision } from './WikiPage'; import { RichTextFlair } from './VoteableContent'; +import WikiPage, { WikiPageRevision } from './WikiPage'; export default class Subreddit extends RedditContent { accounts_active_is_fuzzed: boolean; @@ -108,40 +108,40 @@ export default class Subreddit extends RedditContent { deleteImage(options: { imageName: string; }): Promise; deleteUserFlair(name: string): Promise; editSettings(options: SubredditSettings): Promise; - getBannedUsers(options?: ListingOptions & { name?: string }): Listing; - getContributors(options?: ListingOptions & { name?: string }): Listing; - getControversial(options?: ListingOptions & { time?: string }): Listing; - getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getHot(options?: ListingOptions): Listing; + getBannedUsers(options?: ListingOptions & { name?: string }): Promise>; + getContributors(options?: ListingOptions & { name?: string }): Promise>; + getControversial(options?: ListingOptions & { time?: string }): Promise>; + getEdited(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getHot(options?: ListingOptions): Promise>; getLinkFlairTemplates(linkId: string): Promise; - getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Listing; + getModerationLog(opts?: ListingOptions & { mods?: string[]; type?: ModActionType}): Promise>; getModerators(options?: ListingOptions & { name?: string }): RedditUser[]; - getModmail(options?: ListingOptions): Listing; - getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getMutedUsers(options?: ListingOptions & { name?: string }): Listing; + getModmail(options?: ListingOptions): Promise>; + getModqueue(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getMutedUsers(options?: ListingOptions & { name?: string }): Promise>; getMyFlair(): Promise; - getNew(options?: ListingOptions): Listing; - getNewComments(options?: ListingOptions): Listing; + getNew(options?: ListingOptions): Promise>; + getNewComments(options?: ListingOptions): Promise>; getRandomSubmission(): Promise; getRecommendedSubreddits(options?: { omit?: string[]; }): Promise; - getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; - getRising(options?: ListingOptions): Listing; + getReports(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; + getRising(options?: ListingOptions): Promise>; getRules(): Promise<{ rules: Rule[]; site_rules: string[] }>; getSettings(): Promise; - getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; + getSpam(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; getSticky(options?: { num?: number }): Promise; getStylesheet(): Promise; getSubmitText(): Promise; - getTop(options?: ListingOptions & { time?: Timespan }): Listing; - getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Listing; + getTop(options?: ListingOptions & { time?: Timespan }): Promise>; + getUnmoderated(options?: ListingOptions & { only?: 'links' | 'comments' }): Promise>; getUserFlair(name: string): Promise; - getUserFlairList(options?: ListingOptions & { name?: string; }): Listing; + getUserFlairList(options?: ListingOptions & { name?: string; }): Promise>; getUserFlairTemplates(): Promise; - getWikiBannedUsers(options?: ListingOptions & { name?: string }): Listing; - getWikiContributors(options?: ListingOptions & { name?: string }): Listing; + getWikiBannedUsers(options?: ListingOptions & { name?: string }): Promise>; + getWikiContributors(options?: ListingOptions & { name?: string }): Promise>; getWikiPage(name: string): WikiPage; getWikiPages(): Promise; - getWikiRevisions(options?: ListingOptions): Listing; + getWikiRevisions(options?: ListingOptions): Promise>; hideMyFlair(): Promise; inviteModerator(options: { name: string; permissions?: ModeratorPermission[]; }): Promise; leaveContributor(): Promise; @@ -151,7 +151,7 @@ export default class Subreddit extends RedditContent { removeModerator(options: { name: string; }): Promise; removeWikiContributor(options: { name: string; }): Promise; revokeModeratorInvite(options: { name: string; }): Promise; - search(options: BaseSearchOptions): Listing; + search(options: BaseSearchOptions): Promise>; selectMyFlair(options: { flair_template_id: string; text?: string; }): Promise; setModeratorPermissions(options: { name: string; permissions: ModeratorPermission; }): Promise; setMultipleUserFlairs(flairs: Array<{ diff --git a/types/snoowrap/dist/objects/WikiPage.d.ts b/types/snoowrap/dist/objects/WikiPage.d.ts index ab9de1bdf6..88f16e2f23 100644 --- a/types/snoowrap/dist/objects/WikiPage.d.ts +++ b/types/snoowrap/dist/objects/WikiPage.d.ts @@ -13,8 +13,8 @@ export default class WikiPage extends RedditContent { addEditor(options: { name: string; }): Promise; edit(options: EditOptions): Promise; editSettings(options: Settings): Promise; - getDiscussions(options?: ListingOptions): Listing; - getRevisions(options?: ListingOptions): Listing; + getDiscussions(options?: ListingOptions): Promise>; + getRevisions(options?: ListingOptions): Promise>; getSettings(): Promise; hideRevision(options: { id: string; }): Promise; removeEditor(options: { name: string; }): Promise; diff --git a/types/snoowrap/snoowrap-tests.ts b/types/snoowrap/snoowrap-tests.ts index b83a9514f1..61aca46ffa 100644 --- a/types/snoowrap/snoowrap-tests.ts +++ b/types/snoowrap/snoowrap-tests.ts @@ -81,3 +81,7 @@ export function submissionSearch(query: string, subreddit: string): Promise> { return r.searchSubreddits({ query }); } + +export function getHotFromSubreddit(subreddit: string): Promise> { + return r.getSubreddit(subreddit).getHot({ limit: 10 }); +} diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts index c04c4888f0..d6e808b245 100644 --- a/types/socketcluster-server/scserver.d.ts +++ b/types/socketcluster-server/scserver.d.ts @@ -3,7 +3,7 @@ import { Secret } from "jsonwebtoken"; import { ServerOptions } from "https"; import { IncomingMessage, Server } from "http"; import { SCAuthEngine } from "sc-auth"; -import { SCExchange } from "sc-broker-cluster"; +import { SCExchange, Client } from "sc-broker-cluster"; import WebSocket = require("ws"); import SCServerSocket = require("./scserversocket"); @@ -18,6 +18,7 @@ declare class SCServer extends EventEmitter { readonly MIDDLEWARE_EMIT: "emit"; options: SCServer.SCServerOptions; + brokerEngine: Client; exchange: SCExchange; clients: { @@ -58,7 +59,10 @@ declare class SCServer extends EventEmitter { removeMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; setAuthEngine(authEngine: SCAuthEngine): void; + auth: SCAuthEngine; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + codec: SCServer.SCCodecEngine; close(cb?: (err?: Error) => void): void; @@ -348,7 +352,7 @@ declare namespace SCServer { interface SCCodecEngine { decode: (input: any) => any; - ncode: (object: any) => any; + encode: (object: any) => any; } interface VerifyHandshakeInfo { diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts index 7b32cef72c..c4440a13f3 100644 --- a/types/socketcluster-server/scserversocket.d.ts +++ b/types/socketcluster-server/scserversocket.d.ts @@ -29,15 +29,65 @@ declare class SCServerSocket extends Emitter { constructor(id: string, server: SCServer, socket: WebSocket); + on(event: "error", listener: (error: Error) => void): this; + on(event: "message" | "raw", listener: (message: WebSocket.Data) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data?: any) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCServerSocket.StateChangeData) => void): this; + on(event: "authenticate", listener: (authToken?: SCServer.AuthToken) => void): this; + on(event: "deauthenticate", listener: (oldToken?: SCServer.AuthToken) => void): this; + getState(): "connecting" | "open" | "closed"; + getBytesReceived(): number; + disconnect(code?: number, data?: any): void; + destroy(code?: number, data?: any): void; + terminate(): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + + decode(message: any): any; + encode(object: any): any; + + sendObjectBatch(object: any): void; + sendObjectSingle(object: any): void; + sendObject(object: any, options?: { batch?: boolean }): void; + + emit(event: string, ...args: any[]): boolean; + emit(event: string, data: any, callback?: SCServerSocket.EmitCallback, options?: SCServerSocket.EmitOptions): void; + + triggerAuthenticationEvents(oldState: "authenticated" | "unauthenticated"): void; + getAuthToken(): SCServer.AuthToken; - setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; - deauthenticate(): void; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions, callback?: SCServerSocket.EmitCallback): void; + + deauthenticateSelf(): void; + deauthenticate(callback?: SCServerSocket.EmitCallback): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; isSubscribed(channel?: string): boolean; } export = SCServerSocket; + +declare namespace SCServerSocket { + type EmitCallback = (err: Error, eventObject: EventObject) => void; + + interface EventObject { + event: string; + data?: any; + cid?: number; + } + + interface EmitOptions { + useCache?: boolean; + stringifiedData?: string; + } + + interface StateChangeData { + oldState: "authenticated" | "unauthenticated"; + newState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + } +} diff --git a/types/storybook__addon-info/index.d.ts b/types/storybook__addon-info/index.d.ts index 111f7dc54d..a6c463f5d9 100644 --- a/types/storybook__addon-info/index.d.ts +++ b/types/storybook__addon-info/index.d.ts @@ -6,7 +6,7 @@ // TypeScript Version: 2.8 import * as React from 'react'; -import { RenderFunction } from '@storybook/react'; +import { RenderFunction, StoryDecorator } from '@storybook/react'; export interface WrapStoryProps { storyFn?: RenderFunction; @@ -29,6 +29,10 @@ export interface Options { maxPropStringLength?: number; } +// TODO: it would be better to use type inference for the parameters +// type DecoratorParams = StoryDecorator extends (...a: infer A) => any ? A: never; +export function withInfo(story: RenderFunction, context: { kind: string, story: string }): ReturnType; +// Legacy, but supported export function withInfo(textOrOptions?: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; export function setDefaults(newDefaults: Options): Options; diff --git a/types/storybook__addon-info/storybook__addon-info-tests.tsx b/types/storybook__addon-info/storybook__addon-info-tests.tsx index 46fd799314..505780bf7e 100644 --- a/types/storybook__addon-info/storybook__addon-info-tests.tsx +++ b/types/storybook__addon-info/storybook__addon-info-tests.tsx @@ -1,11 +1,13 @@ /// import * as React from 'react'; -import { storiesOf } from '@storybook/react'; +import { addDecorator, storiesOf } from '@storybook/react'; import { setDefaults, withInfo } from '@storybook/addon-info'; const { Component } = React; +addDecorator(withInfo); + setDefaults({ inline: false, propTables: false diff --git a/types/storybook__addon-notes/index.d.ts b/types/storybook__addon-notes/index.d.ts index b669ce0a9c..096da8fa34 100644 --- a/types/storybook__addon-notes/index.d.ts +++ b/types/storybook__addon-notes/index.d.ts @@ -17,5 +17,9 @@ export type WithNotesOptions = string | { markdownOptions?: MarkedOptions; }; +// It would be preferable to infer the argument types, but that requires TS v 3.1 +// export function withNotes(...args: StoryDecorator extends (...a: infer A) => any ? A : never): ReturnType; +export function withNotes(story: RenderFunction, context: { kind: string, story: string }): ReturnType; +// Less-preferred but still supported: export function withNotes(options?: WithNotesOptions): StoryDecorator; export function withMarkdownNotes(markdown: string, options?: MarkedOptions): StoryDecorator; diff --git a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx b/types/storybook__addon-notes/storybook__addon-notes-tests.tsx index ebf24ce227..edfe0daf14 100644 --- a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx +++ b/types/storybook__addon-notes/storybook__addon-notes-tests.tsx @@ -1,8 +1,11 @@ import * as React from 'react'; -import { storiesOf } from '@storybook/react'; +import { addDecorator, storiesOf } from '@storybook/react'; import { withNotes, withMarkdownNotes, } from '@storybook/addon-notes'; +// New, preferred global registration: +addDecorator(withNotes); + const SIMPLE_MARKDOWN = ` ## Markdown for component diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index bbb003eca0..068755e157 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4642,9 +4642,10 @@ declare namespace Stripe { items: IList; /** - * Hash describing the plan the customer is subscribed to + * Hash describing the plan the customer is subscribed to. Only set if the subscription + * contains a single plan. */ - plan: plans.IPlan; + plan?: plans.IPlan | null; /** * The number of subscriptions for the associated plan diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 1ab41d31e1..924699dd3a 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Ihor Chulinda // Adam Lavin -// Jessica Franco +// Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index aa94ab2aed..19b9afcd5f 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.1 +// Type definitions for styled-system 3.2 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers // Ben McCormick @@ -9,6 +9,7 @@ // Adam Lavin // Joachim Schuler // Adam Misiorny +// Sara F-P // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -41,7 +42,9 @@ export interface LowLevelStylefunctionArguments { scale?: Array; } -export function style(args: LowLevelStylefunctionArguments): {[cssProp: string]: string}; +export function style( + args: LowLevelStylefunctionArguments +): { [cssProp: string]: string }; export type TLengthStyledSystem = string | 0 | number; export type ResponsiveValue = T | Array | { [key: string]: T }; @@ -100,7 +103,7 @@ export function variant(props: VariantArgs): (...args: any[]) => any; export type ObjectOrArray = T[] | { [K: string]: T }; export interface BaseTheme { - breakpoints?: number[]; + breakpoints?: string[] | number[] | object; colors?: ObjectOrArray; fontSizes?: number[]; space?: number[]; diff --git a/types/text-clipper/index.d.ts b/types/text-clipper/index.d.ts new file mode 100644 index 0000000000..1f86ac405b --- /dev/null +++ b/types/text-clipper/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for text-clipper 1.2 +// Project: https://github.com/arendjr/text-clipper +// Definitions by: Krzysztof Grzybek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + breakWords?: boolean; + html?: boolean; + imageWeight?: number; + indicator?: string; + maxLines?: number; +} + +declare function clip(string: string, maxLength: number, options?: Options): string; +export = clip; diff --git a/types/text-clipper/text-clipper-tests.ts b/types/text-clipper/text-clipper-tests.ts new file mode 100644 index 0000000000..f4ca7e6f19 --- /dev/null +++ b/types/text-clipper/text-clipper-tests.ts @@ -0,0 +1,5 @@ +import clip = require('text-clipper'); + +clip('text', 123); // $ExpectType string +clip('text', 123, { breakWords: true, html: false }); // $ExpectType string +clip('text', 123, { imageWeight: 123, indicator: 'something', maxLines: 321 }); // $ExpectType string diff --git a/types/text-clipper/tsconfig.json b/types/text-clipper/tsconfig.json new file mode 100644 index 0000000000..caf06929bb --- /dev/null +++ b/types/text-clipper/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", + "text-clipper-tests.ts" + ] +} diff --git a/types/text-clipper/tslint.json b/types/text-clipper/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/text-clipper/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 639fba5ba5..4866cbfd54 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -867,6 +867,7 @@ export class BufferGeometry extends EventDispatcher { boundingBox: Box3; boundingSphere: Sphere; drawRange: { start: number, count: number }; + userData: {[key: string]: any}; getIndex(): BufferAttribute; setIndex( index: BufferAttribute|number[] ): void; diff --git a/types/trezor-connect/index.d.ts b/types/trezor-connect/index.d.ts index c9c5fb258d..282117efda 100644 --- a/types/trezor-connect/index.d.ts +++ b/types/trezor-connect/index.d.ts @@ -249,7 +249,13 @@ export interface Input { export interface RegularOutput { address: string; amount: string; - script_type: string; + script_type?: string; +} + +export interface InternalOutput { + address_n: number[]; + amount: string; + script_type?: string; } export interface SendMaxOutput { @@ -262,7 +268,7 @@ export interface OpReturnOutput { dataHex: string; } -export type Output = RegularOutput | SendMaxOutput | OpReturnOutput; +export type Output = RegularOutput | InternalOutput | SendMaxOutput | OpReturnOutput; export interface SignTransactionParams extends CommonParams { inputs: Input[]; diff --git a/types/user-event/index.d.ts b/types/user-event/index.d.ts new file mode 100644 index 0000000000..4c4bebb1f8 --- /dev/null +++ b/types/user-event/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for user-event 1.4 +// Project: https://github.com/Gpx/user-event#readme +// Definitions by: Wu Haotian +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface UserOpts { + allAtOnce?: boolean; + delay?: number; +} +declare const userEvent: { + click: (element: Element | Window) => void; + dblClick: (element: Element | Window) => void; + type: ( + element: Element | Window, + text: string, + userOpts?: UserOpts + ) => Promise; +}; + +export default userEvent; diff --git a/types/user-event/tsconfig.json b/types/user-event/tsconfig.json new file mode 100644 index 0000000000..38348b184c --- /dev/null +++ b/types/user-event/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["dom", "es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "user-event-tests.ts"] +} diff --git a/types/user-event/tslint.json b/types/user-event/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/user-event/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/user-event/user-event-tests.ts b/types/user-event/user-event-tests.ts new file mode 100644 index 0000000000..0ecf6eb439 --- /dev/null +++ b/types/user-event/user-event-tests.ts @@ -0,0 +1,11 @@ +import userEvent, { UserOpts } from "user-event"; + +userEvent.click(document.body); // $ExpectType void +userEvent.dblClick(window); // $ExpectType void +userEvent.type(document.body, "s"); // $ExpectType Promise +userEvent.type(document.body, "s", {}); // $ExpectType Promise +userEvent.type(document.body, "s", { delay: 5000 }); // $ExpectType Promise +userEvent.type(document.body, "s", { allAtOnce: true }); // $ExpectType Promise +userEvent.type(document.body, "s", { delay: 1000, allAtOnce: false }); // $ExpectType Promise + +const u: UserOpts = { delay: 20 }; diff --git a/types/vinyl-fs/.editorconfig b/types/vinyl-fs/.editorconfig deleted file mode 100644 index 831139084b..0000000000 --- a/types/vinyl-fs/.editorconfig +++ /dev/null @@ -1,3 +0,0 @@ -[*.ts] -indent_style = space -indent_size = 3 diff --git a/types/vinyl-fs/index.d.ts b/types/vinyl-fs/index.d.ts index d35dd6bcef..f437276c4e 100644 --- a/types/vinyl-fs/index.d.ts +++ b/types/vinyl-fs/index.d.ts @@ -2,16 +2,17 @@ // Project: https://github.com/wearefractal/vinyl-fs // Definitions by: vvakame // remisery +// TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// declare global { - namespace NodeJS { - interface WritableStream { - write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; - } - } + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } } import * as _events from 'events'; @@ -19,128 +20,128 @@ import * as File from 'vinyl'; import * as globStream from 'glob-stream'; export interface SrcOptions extends globStream.Options { - /** Prevents stream from emitting an error when file not found. */ - allowEmpty?: boolean; + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; - /** Specifies the working directory the folder is relative to */ - cwd?: string; + /** Specifies the working directory the folder is relative to */ + cwd?: string; - /** - * Specifies the folder relative to the cwd - * This is used to determine the file names when saving in .dest() - * Default: where the glob begins - */ - base?: string; + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; - /** - * Setting this to false will make file.contents a paused stream - * If true it will buffer the file contents - * Default: true - */ - buffer?: boolean; + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; - /** - * The mode the directory should be created with. - * Default: the process mode - */ - dirMode?: number; + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; - /** - * Whether or not you want globs to match on dot files or not - * (e.g., `.gitignore`). - */ - dot?: boolean; + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; - /** - * Whether or not to recursively resolve symlinks to their targets. - * Setting to `false` to preserve them as symlinks and make `file.symlink` - * equal the original symlink's target path. - * Default: true - */ - followSymlinks?: boolean; + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; - /** - * Setting this to false will ignore the contents of the file and disable - * writing to disk to speed up operations - * Default: true - */ - read?: boolean; + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; - /** - * Whether or not the symlink should be relative or absolute. - * Default: false - */ - relative?: boolean; + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; - /** Only find files that have been modified since the time specified */ - since?: Date|number; + /** Only find files that have been modified since the time specified */ + since?: Date | number; - /** - * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` - * if you need the BOM for some reason. - */ - stripBOM?: boolean; + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; - /** - * Setting this to true will create a duplex stream, one that passes - * through items and emits globbed files. - * Default: false - */ - passthrough?: boolean; + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; - /** - * Setting this to true will enable sourcemaps. - * Default: false - */ - sourcemaps?: boolean; + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; - /** - * Whether or not to recursively resolve symlinks to their targets. Setting to false to - * preserve them as symlinks and make file.symlink equal the original symlink's target path. - * Default: false - */ - resolveSymlinks?: boolean; - /** - * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. - * Default: true - */ - removeBOM?: boolean; + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; } export interface DestOptions { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** - * Specify the mode the files should be created with - * Default is the mode of the input file (file.stat.mode) - * or the process mode if the input file has no mode property - */ - mode?: number|string; + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number | string; - /** Specify the mode the directory should be created with. Default is the process mode */ - dirMode?: number|string; + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number | string; - /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ - overwrite?: boolean; + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; - /** - * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if - * specified as true. Specifying a string path will write external sourcemaps at the given path. - */ - sourcemaps?: true | string; + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; - /** - * When creating a symlink, whether or not the created symlink should be relative. If false, - * the symlink will be absolute. Note: This option will be ignored if a junction is being created. - */ - relativeSymlinks?: boolean; + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; - /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ - useJunctions?: boolean; + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; } /** @@ -152,32 +153,6 @@ export interface DestOptions { */ export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; -/** - * This is just a glob-watcher - * - * @param globs Takes a glob string or an array of glob strings as the first argument - * Globs are executed in order, so negations should follow positive globs - * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) - */ -export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; - -/** - * This is just a glob-watcher - * - * @param globs Takes a glob string or an array of glob strings as the first argument - * Globs are executed in order, so negations should follow positive globs - * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) - */ -export function watch( - globs: string|string[], - opt?: { - interval?: number; - debounceDelay?: number; - cwd?: string; - maxListeners?(): number; - }, - cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; - /** * On write the stream will save the vinyl File to disk at the folder/cwd specified. * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. @@ -207,20 +182,20 @@ export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStr * cwd, base, and path will be overwritten to match the folder */ export function symlink(folder: string, opts?: { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** Specify the mode the directory should be created with. Default is the process mode */ - mode?: number|string; + /** Specify the mode the directory should be created with. Default is the process mode */ + mode?: number | string; - /** - * Specify the mode the directory should be created with - * Default is the process mode - */ - dirMode?: number + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number }): NodeJS.ReadWriteStream; /** @@ -229,17 +204,16 @@ export function symlink(folder: string, opts?: { * The file will be modified after being written to this stream: * cwd, base, and path will be overwritten to match the folder */ -export function symlink(getFolderPath: (File: File) => string, opts?: - { - /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ - cwd?: string; +export function symlink(getFolderPath: (File: File) => string, opts?: { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; - /** - * Specify the mode the directory should be created with - * Default is the process mode - */ - dirMode?: number - }): NodeJS.ReadWriteStream; + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number +}): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/tsconfig.json b/types/vinyl-fs/tsconfig.json index 6f041838fd..7780364fc3 100644 --- a/types/vinyl-fs/tsconfig.json +++ b/types/vinyl-fs/tsconfig.json @@ -5,8 +5,8 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/vinyl-fs/tslint.json b/types/vinyl-fs/tslint.json index f2821adb2b..f93cf8562a 100644 --- a/types/vinyl-fs/tslint.json +++ b/types/vinyl-fs/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json" } diff --git a/types/vinyl-fs/v0/index.d.ts b/types/vinyl-fs/v0/index.d.ts new file mode 100644 index 0000000000..5b30adcea0 --- /dev/null +++ b/types/vinyl-fs/v0/index.d.ts @@ -0,0 +1,201 @@ +// Type definitions for vinyl-fs 0.3 +// Project: https://github.com/wearefractal/vinyl-fs +// Definitions by: vvakame +// remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } +} + +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +export interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; + + /** Specifies the working directory the folder is relative to */ + cwd?: string; + + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; + + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; + + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; + + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; + + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; + + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; + + /** Only find files that have been modified since the time specified */ + since?: Date|number; + + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; + + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; + + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; +} + +export interface DestOptions { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number|string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number|string; + + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; + + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; + + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; + + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; +} + +/** + * Gets files that match the glob and converts them into the vinyl format + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream + */ +export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?(): number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param folder destination folder + */ +export function dest(folder: string, opt?: DestOptions): NodeJS.ReadWriteStream; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param getFolderPath function that takes in a file and returns a folder path + */ +export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/v0/tsconfig.json b/types/vinyl-fs/v0/tsconfig.json new file mode 100644 index 0000000000..08ae9db69c --- /dev/null +++ b/types/vinyl-fs/v0/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "vinyl-fs": [ + "vinyl-fs/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} \ No newline at end of file diff --git a/types/vinyl-fs/v0/tslint.json b/types/vinyl-fs/v0/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/vinyl-fs/v0/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/vinyl-fs/v0/vinyl-fs-tests.ts b/types/vinyl-fs/v0/vinyl-fs-tests.ts new file mode 100644 index 0000000000..4d0316a0a0 --- /dev/null +++ b/types/vinyl-fs/v0/vinyl-fs-tests.ts @@ -0,0 +1,534 @@ +// from src + +import * as vfs from 'vinyl-fs'; + +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); + +// import bufEqual = require('buffer-equal'); +declare const bufEqual: any; +// import through = require('through2'); +declare const through: any; +import File = require('vinyl'); +// const spies = require('./spy'); +declare const spies: any; + +// Stub mocha functions +const {describe, it, before, after, beforeEach, afterEach} = null as any as { + [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & {only: any, skip: any}; +}; + +// TODO: These aren't useful as types tests since they take `any`. +declare const should: ShouldStatic; +interface ShouldStatic { + exist(obj: any, desc?: string): void; + not: this; +} +declare global { + interface Object { + should: { equal(obj: any): void; }; + } +} + +declare const gulp: any; +let bufferStream: any; + +let dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +describe('source stream', () => { + it('should explode on invalid glob (empty)', done => { + let stream: any; + try { + stream = gulp.src(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (number)', done => { + let stream: any; + try { + stream = gulp.src(123); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (empty array)', done => { + let stream: any; + try { + stream = gulp.src([]); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: expectedPath, + contents: expectedContent + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/nothing.coffee"); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should glob a file with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with default settings and relative cwd', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a directory with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/wow"); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + buffered[0].isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/wow/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with with no contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + should.not.exist(buffered[0].contents); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, read: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with streaming contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isStream().should.equal(true); + + let contentBuffer = new Buffer([]); + const contentBufferStream = through(dataWrap((data: any) => { + contentBuffer = Buffer.concat([contentBuffer, data]); + })); + buffered[0].contents.pipe(contentBufferStream); + buffered[0].contents.once('end', () => { + bufEqual(contentBuffer, expectedContent); + done(); + }); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, buffer: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); +}); + +// from dest +// const vfs = require('../'); + +// const path = require('path'); +// const fs = require('graceful-fs'); +import rimraf = require('rimraf'); + +// const bufEqual = require('buffer-equal'); +// const through = require('through2'); +// const File = require('vinyl'); + +// const should = require('should'); +// require('mocha'); + +const wipeOut = (cb: any) => { + rimraf(path.join(__dirname, "./out-fixtures/"), cb); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +const realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('dest stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', done => { + let stream: any; + try { + stream = gulp.dest(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest(path.join(__dirname, "./out-fixtures/")); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should not write null files', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(false); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + fs.lstatSync(expectedPath).isDirectory().should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should allow piping multiple dests in streaming mode', done => { + const inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); + const inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); + const inputBase = path.join(__dirname, "./out-fixtures/"); + const srcPath = path.join(__dirname, "./fixtures/test.coffee"); + const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const content = fs.readFileSync(srcPath); + const rename = through.obj((file: any, _: any, next: any) => { + file.path = inputPath2; + this.push(file); + next(); + }); + + stream1.on('data', (file: any) => { + file.path.should.equal(inputPath1); + }); + + stream1.pipe(rename).pipe(stream2); + stream2.on('data', (file: any) => { + file.path.should.equal(inputPath2); + }).once('end', () => { + fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); + fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); + done(); + }); + + const file = new File({ + base: inputBase, + path: inputPath1, + cwd: __dirname, + contents: content + }); + + stream1.write(file); + stream1.end(); + }); +}); diff --git a/types/vinyl-fs/v1/index.d.ts b/types/vinyl-fs/v1/index.d.ts new file mode 100644 index 0000000000..2159567816 --- /dev/null +++ b/types/vinyl-fs/v1/index.d.ts @@ -0,0 +1,245 @@ +// Type definitions for vinyl-fs 1.0 +// Project: https://github.com/wearefractal/vinyl-fs +// Definitions by: vvakame +// remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace NodeJS { + interface WritableStream { + write(buffer: any/* Vinyl.File */, cb?: (err?: Error | null) => void): boolean; + } + } +} + +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +export interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; + + /** Specifies the working directory the folder is relative to */ + cwd?: string; + + /** + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ + base?: string; + + /** + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ + buffer?: boolean; + + /** + * The mode the directory should be created with. + * Default: the process mode + */ + dirMode?: number; + + /** + * Whether or not you want globs to match on dot files or not + * (e.g., `.gitignore`). + */ + dot?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. + * Setting to `false` to preserve them as symlinks and make `file.symlink` + * equal the original symlink's target path. + * Default: true + */ + followSymlinks?: boolean; + + /** + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ + read?: boolean; + + /** + * Whether or not the symlink should be relative or absolute. + * Default: false + */ + relative?: boolean; + + /** Only find files that have been modified since the time specified */ + since?: Date|number; + + /** + * Causes the BOM to be stripped on UTF-8 encoded files. Set to `false` + * if you need the BOM for some reason. + */ + stripBOM?: boolean; + + /** + * Setting this to true will create a duplex stream, one that passes + * through items and emits globbed files. + * Default: false + */ + passthrough?: boolean; + + /** + * Setting this to true will enable sourcemaps. + * Default: false + */ + sourcemaps?: boolean; + + /** + * Whether or not to recursively resolve symlinks to their targets. Setting to false to + * preserve them as symlinks and make file.symlink equal the original symlink's target path. + * Default: false + */ + resolveSymlinks?: boolean; + /** + * Causes the BOM to be removed on UTF-8 encoded files. Set to false if you need the BOM for some reason. + * Default: true + */ + removeBOM?: boolean; +} + +export interface DestOptions { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the files should be created with + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ + mode?: number|string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + dirMode?: number|string; + + /** Specify if existing files with the same path should be overwritten or not. Default is true, to always overwrite existing files */ + overwrite?: boolean; + + /** + * Enables sourcemap support on files passed through the stream. Will write inline soucemaps if + * specified as true. Specifying a string path will write external sourcemaps at the given path. + */ + sourcemaps?: true | string; + + /** + * When creating a symlink, whether or not the created symlink should be relative. If false, + * the symlink will be absolute. Note: This option will be ignored if a junction is being created. + */ + relativeSymlinks?: boolean; + + /* When creating a symlink, whether or not a directory symlink should be created as a junction. */ + useJunctions?: boolean; +} + +/** + * Gets files that match the glob and converts them into the vinyl format + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream + */ +export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ +export function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?(): number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param folder destination folder + */ +export function dest(folder: string, opt?: DestOptions): NodeJS.ReadWriteStream; + +/** + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param getFolderPath function that takes in a file and returns a folder path + */ +export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStream; + +/** + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd specified. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ +export function symlink(folder: string, opts?: { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** Specify the mode the directory should be created with. Default is the process mode */ + mode?: number|string; + + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number +}): NodeJS.ReadWriteStream; + +/** + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd generated from getFolderPath. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ +export function symlink(getFolderPath: (File: File) => string, opts?: + { + /** + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ + cwd?: string; + + /** + * Specify the mode the directory should be created with + * Default is the process mode + */ + dirMode?: number + }): NodeJS.ReadWriteStream; diff --git a/types/vinyl-fs/v1/tsconfig.json b/types/vinyl-fs/v1/tsconfig.json new file mode 100644 index 0000000000..4e7c14e299 --- /dev/null +++ b/types/vinyl-fs/v1/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "vinyl-fs": [ + "vinyl-fs/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} \ No newline at end of file diff --git a/types/vinyl-fs/v1/tslint.json b/types/vinyl-fs/v1/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/vinyl-fs/v1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/vinyl-fs/v1/vinyl-fs-tests.ts b/types/vinyl-fs/v1/vinyl-fs-tests.ts new file mode 100644 index 0000000000..5b29b0465d --- /dev/null +++ b/types/vinyl-fs/v1/vinyl-fs-tests.ts @@ -0,0 +1,919 @@ +// from src + +import * as vfs from 'vinyl-fs'; + +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); + +// import bufEqual = require('buffer-equal'); +declare const bufEqual: any; +// import through = require('through2'); +declare const through: any; +import File = require('vinyl'); +// const spies = require('./spy'); +declare const spies: any; + +// Stub mocha functions +const {describe, it, before, after, beforeEach, afterEach} = null as any as { + [s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & {only: any, skip: any}; +}; + +// TODO: These aren't useful as types tests since they take `any`. +declare const should: ShouldStatic; +interface ShouldStatic { + exist(obj: any, desc?: string): void; + not: this; +} +declare global { + interface Object { + should: { equal(obj: any): void; }; + } +} + +declare const gulp: any; +let bufferStream: any; + +let dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +describe('source stream', () => { + it('should explode on invalid glob (empty)', done => { + let stream: any; + try { + stream = gulp.src(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (number)', done => { + let stream: any; + try { + stream = gulp.src(123); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should explode on invalid glob (empty array)', done => { + let stream: any; + try { + stream = gulp.src([]); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: expectedPath, + contents: expectedContent + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/nothing.coffee"); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should glob a file with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with default settings and relative cwd', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isBuffer().should.equal(true); + bufEqual(buffered[0].contents, expectedContent).should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a directory with default settings', done => { + const expectedPath = path.join(__dirname, "./fixtures/wow"); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + buffered[0].isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.src("./fixtures/wow/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with with no contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].path.should.equal(expectedPath); + buffered[0].isNull().should.equal(true); + should.not.exist(buffered[0].contents); + done(); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, read: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); + + it('should glob a file with streaming contents', done => { + const expectedPath = path.join(__dirname, "./fixtures/test.coffee"); + const expectedContent = fs.readFileSync(expectedPath); + + const onEnd = () => { + buffered.length.should.equal(1); + should.exist(buffered[0].stat); + buffered[0].path.should.equal(expectedPath); + buffered[0].isStream().should.equal(true); + + let contentBuffer = new Buffer([]); + const contentBufferStream = through(dataWrap((data: any) => { + contentBuffer = Buffer.concat([contentBuffer, data]); + })); + buffered[0].contents.pipe(contentBufferStream); + buffered[0].contents.once('end', () => { + bufEqual(contentBuffer, expectedContent); + done(); + }); + }; + + const stream = vfs.src("./fixtures/*.coffee", { cwd: __dirname, buffer: false }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + }); +}); + +// from dest +// const vfs = require('../'); + +// const path = require('path'); +// const fs = require('graceful-fs'); +import rimraf = require('rimraf'); + +// const bufEqual = require('buffer-equal'); +// const through = require('through2'); +// const File = require('vinyl'); + +// const should = require('should'); +// require('mocha'); + +let wipeOut = (cb: any) => { + rimraf(path.join(__dirname, "./out-fixtures/"), cb); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +let realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('dest stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', done => { + let stream: any; + try { + stream = gulp.dest(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.dest(path.join(__dirname, "./out-fixtures/")); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should not write null files', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(false); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test.coffee"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, "./fixtures/test"); + const inputBase = path.join(__dirname, "./fixtures/"); + const expectedPath = path.join(__dirname, "./out-fixtures/test"); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, "./out-fixtures"); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + fs.lstatSync(expectedPath).isDirectory().should.equal(true); + realMode(fs.lstatSync(expectedPath).mode).should.equal(expectedMode); + done(); + }; + + const stream = vfs.dest("./out-fixtures/", { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should allow piping multiple dests in streaming mode', done => { + const inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); + const inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); + const inputBase = path.join(__dirname, "./out-fixtures/"); + const srcPath = path.join(__dirname, "./fixtures/test.coffee"); + const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); + const content = fs.readFileSync(srcPath); + const rename = through.obj((file: any, _: any, next: any) => { + file.path = inputPath2; + this.push(file); + next(); + }); + + stream1.on('data', (file: any) => { + file.path.should.equal(inputPath1); + }); + + stream1.pipe(rename).pipe(stream2); + stream2.on('data', (file: any) => { + file.path.should.equal(inputPath2); + }).once('end', () => { + fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); + fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); + done(); + }); + + const file = new File({ + base: inputBase, + path: inputPath1, + cwd: __dirname, + contents: content + }); + + stream1.write(file); + stream1.end(); + }); +}); + +// This test is from + +const chmodSpy = spies.chmodSpy; +const statSpy = spies.statSpy; + +wipeOut = (cb: any) => { + rimraf(path.join(__dirname, './out-fixtures/'), cb); + spies.setError('false'); + statSpy.reset(); + chmodSpy.reset(); +}; + +dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { + fn(data); + cb(); + }; +}; + +realMode = (n: any) => { + return n & parseInt("07777", 8); +}; + +describe('symlink stream', () => { + beforeEach(wipeOut); + afterEach(wipeOut); + + it('should explode on invalid folder', (done: any) => { + let stream: any; + try { + stream = gulp.symlink(); + } catch (err) { + should.exist(err); + should.not.exist(stream); + done(); + } + }); + + it('should pass through writes with cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should pass through writes with default cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + + const expectedFile = new File({ + base: __dirname, + cwd: __dirname, + path: inputPath, + contents: null + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + done(); + }; + + const stream = vfs.symlink(path.join(__dirname, './out-fixtures/')); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should make link to the right folder with relative cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder with function and relative cwd', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedContents = fs.readFileSync(inputPath); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink(file => { + should.exist(file); + file.should.equal(expectedFile); + return './out-fixtures'; + }, { cwd: path.relative(process.cwd(), __dirname) }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write buffer files to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should write streaming files to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const contentStream = through.obj(); + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: contentStream, + stat: { + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.existsSync(expectedPath).should.equal(true); + bufEqual(fs.readFileSync(expectedPath), expectedContents).should.equal(true); + fs.readlinkSync(expectedPath).should.equal(inputPath); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + setTimeout(() => { + contentStream.write(expectedContents); + contentStream.end(); + }, 100); + stream.end(); + }); + + it('should write directories to the right folder', done => { + const inputPath = path.join(__dirname, './fixtures/wow'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/wow'); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0655", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: null, + stat: { + isDirectory: () => true, + mode: expectedMode + } as fs.Stats + }); + + const onEnd = () => { + buffered.length.should.equal(1); + buffered[0].should.equal(expectedFile); + buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); + buffered[0].base.should.equal(expectedBase, 'base should have changed'); + buffered[0].path.should.equal(expectedPath, 'path should have changed'); + fs.readlinkSync(expectedPath).should.equal(inputPath); + fs.lstatSync(expectedPath).isDirectory().should.equal(false); + fs.statSync(expectedPath).isDirectory().should.equal(true); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + stream.pipe(bufferStream); + stream.write(expectedFile); + stream.end(); + }); + + it('should use different modes for files and directories', done => { + const inputBase = path.join(__dirname, './fixtures'); + const inputPath = path.join(__dirname, './fixtures/wow/suchempty'); + const expectedBase = path.join(__dirname, './out-fixtures/wow'); + const expectedDirMode = parseInt("0755", 8); + const expectedFileMode = parseInt("0655", 8); + + const firstFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + stat: fs.statSync(inputPath) + }); + + const onEnd = () => { + realMode(fs.lstatSync(expectedBase).mode).should.equal(expectedDirMode); + realMode(buffered[0].stat.mode).should.equal(expectedFileMode); + done(); + }; + + const stream = vfs.symlink('./out-fixtures/', { + cwd: __dirname, + mode: expectedFileMode, + dirMode: expectedDirMode + }); + + const buffered: any[] = []; + bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); + + stream.pipe(bufferStream); + stream.write(firstFile); + stream.end(); + }); + + it('should report IO errors', done => { + const inputPath = path.join(__dirname, './fixtures/test.coffee'); + const inputBase = path.join(__dirname, './fixtures/'); + const expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); + const expectedContents = fs.readFileSync(inputPath); + const expectedCwd = __dirname; + const expectedBase = path.join(__dirname, './out-fixtures'); + const expectedMode = parseInt("0722", 8); + + const expectedFile = new File({ + base: inputBase, + cwd: __dirname, + path: inputPath, + contents: expectedContents, + stat: { + mode: expectedMode + } as fs.Stats + }); + + fs.mkdirSync(expectedBase); + fs.chmodSync(expectedBase, 0); + + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + stream.on('error', (err: any) => { + err.code.should.equal('EACCES'); + done(); + }); + stream.write(expectedFile); + }); + + ['end', 'finish'].forEach(eventName => { + it(`should emit ${eventName} event`, done => { + const srcPath = path.join(__dirname, './fixtures/test.coffee'); + const stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); + + stream.on(eventName, () => { + done(); + }); + + const file = new File({ + path: srcPath, + cwd: __dirname, + contents: new Buffer("1234567890") + }); + + stream.write(file); + stream.end(); + }); + }); + it('should check if it"s a vinyl file', () => { + const srcPath = path.join(__dirname, './fixtures/test.coffee'); + const options = { + path: srcPath, + cwd: __dirname, + contents: new Buffer("1234567890") + }; + const file = new File(options); + File.isVinyl(file).should.equal(true); + File.isVinyl(options).should.equal(false); + }); +}); diff --git a/types/vinyl-fs/vinyl-fs-tests.ts b/types/vinyl-fs/vinyl-fs-tests.ts index aac3c4f49e..2a38bcf811 100644 --- a/types/vinyl-fs/vinyl-fs-tests.ts +++ b/types/vinyl-fs/vinyl-fs-tests.ts @@ -3,13 +3,14 @@ import * as vfs from 'vinyl-fs'; import * as path from 'path'; -import * as fs from 'fs'; // require('graceful-fs'); +import * as fs from 'fs'; +import * as stream from 'stream'; // import bufEqual = require('buffer-equal'); declare const bufEqual: any; -// import through = require('through2'); -declare const through: any; +import gulp = require('gulp'); import File = require('vinyl'); +import through = require('through2'); // const spies = require('./spy'); declare const spies: any; @@ -30,8 +31,7 @@ declare global { } } -declare const gulp: any; -let bufferStream: any; +let bufferStream: stream.Transform; let dataWrap = (fn: any) => { return (data: any, enc: any, cb: any) => { @@ -44,7 +44,7 @@ describe('source stream', () => { it('should explode on invalid glob (empty)', done => { let stream: any; try { - stream = gulp.src(); + stream = ( gulp).src(); } catch (err) { should.exist(err); should.not.exist(stream); @@ -55,7 +55,7 @@ describe('source stream', () => { it('should explode on invalid glob (number)', done => { let stream: any; try { - stream = gulp.src(123); + stream = gulp.src( 123); } catch (err) { should.exist(err); should.not.exist(stream); @@ -243,7 +243,7 @@ describe('dest stream', () => { it('should explode on invalid folder', done => { let stream: any; try { - stream = gulp.dest(); + stream = ( gulp).dest(); } catch (err) { should.exist(err); should.not.exist(stream); @@ -383,7 +383,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -424,7 +424,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -467,7 +467,7 @@ describe('dest stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -502,7 +502,7 @@ describe('dest stream', () => { const stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); const stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); const content = fs.readFileSync(srcPath); - const rename = through.obj((file: any, _: any, next: any) => { + const rename = through.obj(function t(this: stream.Transform, file: any, _: any, next: any) { file.path = inputPath2; this.push(file); next(); @@ -563,7 +563,7 @@ describe('symlink stream', () => { it('should explode on invalid folder', (done: any) => { let stream: any; try { - stream = gulp.symlink(); + stream = ( gulp).symlink(); } catch (err) { should.exist(err); should.not.exist(stream); @@ -711,7 +711,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -752,7 +752,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } as fs.Stats }); @@ -795,7 +795,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: null, - stat: { + stat: { isDirectory: () => true, mode: expectedMode } as fs.Stats @@ -870,7 +870,7 @@ describe('symlink stream', () => { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } as fs.Stats }); diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 84ff769270..187c01c9b7 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -459,7 +459,7 @@ export class DataSet { * @returns When no item is found, null is returned when a single item was requested, * and and empty Array is returned in case of multiple id's. */ - get(id: IdType, options?: DataSelectionOptions): T; + get(id: IdType, options?: DataSelectionOptions): T|null; /** * Get multiple items from the DataSet. @@ -494,7 +494,7 @@ export class DataSet { * @param [options] Optional options. * @returns The mapped items. */ - map(callback: (item: T, id: IdType) => any, options?: DataSelectionOptions): any[]; + map(callback: (item: T, id: IdType) => M, options?: DataSelectionOptions): M[]; /** * Find the item with maximum value of specified field. @@ -589,7 +589,7 @@ export interface DataSelectionOptions { /** * Order the items by a field name or custom sort function. */ - order?: string | any; + order?: string | ((a: T, b: T) => number); /** * Determine the type of output of the get function. @@ -597,7 +597,7 @@ export interface DataSelectionOptions { * The default returnType is an Array. * The Object type will return a JSON object with the ID's as keys. */ - returnType?: string; + returnType?: "Array" | "Object"; } export class DataView { diff --git a/types/watchpack/index.d.ts b/types/watchpack/index.d.ts index 880e0d8a6d..4ef4ad2e67 100644 --- a/types/watchpack/index.d.ts +++ b/types/watchpack/index.d.ts @@ -23,7 +23,7 @@ declare class Watchpack extends EventEmitter { constructor(options: Watchpack.WatchOptions); - watch(files: string[], directories: string[], startTime: number): void; + watch(files: string[], directories: string[], startTime?: number): void; close(): void; diff --git a/types/watchpack/watchpack-tests.ts b/types/watchpack/watchpack-tests.ts index 7ae28bc514..f3eb459aef 100644 --- a/types/watchpack/watchpack-tests.ts +++ b/types/watchpack/watchpack-tests.ts @@ -2,6 +2,7 @@ import Watchpack = require('watchpack'); const watch = new Watchpack({}); watch.watch(['test.js'], ['lib/'], 1000); +watch.watch(['test.js'], ['lib/']); let time: number; time = watch.getTimes()['test.js']; diff --git a/types/webpack-env/index.d.ts b/types/webpack-env/index.d.ts index d9047f965e..293f06797d 100644 --- a/types/webpack-env/index.d.ts +++ b/types/webpack-env/index.d.ts @@ -32,7 +32,7 @@ declare namespace __WebpackModuleApi { * This creates a chunk. The chunk can be named. If a chunk with this name already exists, the dependencies are merged into that chunk and that chunk is used. */ ensure(paths: string[], callback: (require: NodeRequire) => void, errorCallback?: (error: any) => void, chunkName?: string): void; - context(path: string, deep?: boolean, filter?: RegExp): RequireContext; + context(path: string, deep?: boolean, filter?: RegExp, mode?: "sync" | "eager" | "weak" | "lazy" | "lazy-once"): RequireContext; /** * Returns the module id of a dependency. The call is sync. No request to the server is fired. The compiler ensures that the dependency is available. * diff --git a/types/xxhashjs/index.d.ts b/types/xxhashjs/index.d.ts index 40c45cf3ab..9c9d7e4318 100644 --- a/types/xxhashjs/index.d.ts +++ b/types/xxhashjs/index.d.ts @@ -1,19 +1,29 @@ -// Type definitions for xxhashjs 0.1 +// Type definitions for xxhashjs 0.2 // Project: https://github.com/pierrec/js-xxhash // Definitions by: Dibyo Majumdar +// Nick Zahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + export as namespace XXH; +// Ideally we would have a type definition for the "cuint" package. +// The following interface `UINT` is to resolve the bare minimum. +interface UINT { + toNumber(): number; + toString(radix?: number): string; +} + export interface HashObject { - init(seed: number): this; - update(data: string | ArrayBuffer): this; - digest(): number; + init(seed: number): this; + update(data: string | ArrayBuffer | Buffer): this; + digest(): UINT; } export interface HashInterface { - (seed?: number): HashObject; - (data: string | ArrayBuffer, seed: number): number; + (seed?: number): HashObject; + (data: string | ArrayBuffer | Buffer, seed: number): UINT; } export const h32: HashInterface; diff --git a/types/xxhashjs/xxhashjs-tests.ts b/types/xxhashjs/xxhashjs-tests.ts index ee2d7ef8f3..889bf9bb40 100644 --- a/types/xxhashjs/xxhashjs-tests.ts +++ b/types/xxhashjs/xxhashjs-tests.ts @@ -1,7 +1,37 @@ import XXH from 'xxhashjs'; -// examples adapted from https://github.com/pierrec/js-xxhash -const h1 = XXH.h32('abcd', 0xABCD).toString(16); +// Test data +const seed = 0xABCD; +const stringData = 'abcd'; +const arrayBufferData = new ArrayBuffer(4); +const bufferData = Buffer.from([1, 2, 3, 4]); -const H = XXH.h32(0xABCD); -const h2 = H.update('abcd').digest().toString(16); +// Test XXH.h32 methods, initialising with string data +const value32_1 = XXH.h32(stringData, seed); +value32_1.toString(); +value32_1.toString(16); +value32_1.toNumber(); + +const value32_2 = XXH.h32(seed).update(stringData).digest(); +value32_2.toString(); +value32_2.toString(16); +value32_2.toNumber(); + +// Test XXH.h64 methods, initialising with string data +const value64_1 = XXH.h64(stringData, seed); +value64_1.toString(); +value64_1.toString(16); +value64_1.toNumber(); + +const value64_2 = XXH.h64(seed).update(stringData).digest(); +value64_2.toString(); +value64_2.toString(16); +value64_2.toNumber(); + +// Initialise with ArrayBuffer +XXH.h32(arrayBufferData, seed); +XXH.h64(arrayBufferData, seed); + +// Initialise with Buffer +XXH.h32(bufferData, seed); +XXH.h64(bufferData, seed); diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index ffba765581..9f3cb687a2 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -8,6 +8,7 @@ // Vincent Pizzo // Robert Bullen // Yusuke Sato +// Dan Rumney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -66,7 +67,8 @@ export interface Schema { strict(isStrict: boolean): this; strip(strip: boolean): this; withMutation(fn: (current: this) => void): void; - default(value?: any): this; + default(value: any): this; + default(): T; nullable(isNullable: boolean): this; required(message?: TestOptionsMessage): this; notRequired(): this;