diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 3daca57647..7ca266e6ce 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -4,6 +4,7 @@ // Matt Durrant // Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace auth0; @@ -172,7 +173,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(callback: Auth0Callback): void; + parseHash(callback: Auth0Callback): void; /** * Parse the url hash and extract the returned tokens depending on the transaction. @@ -183,7 +184,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(options: ParseHashOptions, callback: Auth0Callback): void; + parseHash(options: ParseHashOptions, callback: Auth0Callback): void; /** * Decodes the id_token and verifies the nonce. @@ -482,7 +483,7 @@ export class CrossOriginAuthentication { callback(): void; } -export type Auth0Callback = (error: null | Auth0Error, result: T) => void; +export type Auth0Callback = (error: null | E, result: T) => void; export interface TokenProvider { enableCache?: boolean; @@ -522,18 +523,51 @@ export interface PasswordlessAuthOptions { email: string; } +/** + * These are error codes defined by the auth0-js lib. + */ +export type LibErrorCodes = 'timeout' | 'request_error' | 'invalid_token'; + +/** + * The user was not logged in at Auth0, so silent authentication is not possible. + */ +export type LoginRequiredErrorCode = 'login_required'; + +/** + * The user was logged in at Auth0 and has authorized the application, but needs to + * be redirected elsewhere before authentication can be completed; for example, when + * using a redirect rule. + */ +export type InteractionRequiredErrorCode = 'interaction_required'; + +/** + * The user was logged in at Auth0, but needs to give consent to authorize the application. + */ +export type ConsentRequiredErrorCode = 'consent_required'; + +/** + * These are error codes defined by the OpenID Connect specification. + */ +export type SpecErrorCodes = + LoginRequiredErrorCode | + InteractionRequiredErrorCode | + ConsentRequiredErrorCode | + 'account_selection_required' | + 'invalid_request_uri' | + 'invalid_request_object' | + 'request_not_supported' | + 'request_uri_not_supported' | + 'registration_not_supported'; + export interface Auth0Error { - error?: any; - errorDescription?: string; - code?: string; - description?: string; - name?: string; - policy?: string; - original?: any; - statusCode?: number; - statusText?: string; + error: LibErrorCodes | SpecErrorCodes | string; + errorDescription: string; } +export type Auth0ParseHashError = Auth0Error & { + state?: string; +}; + /** * The contents of the authResult object returned by {@link WebAuth#parseHash } */ diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 8c3a7da850..2916ec58c8 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -5,6 +5,7 @@ // Larry Faudree // Will Caulfield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 /// diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 440f3da7e0..00b71132e9 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -8,6 +8,7 @@ declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; +declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; declare let customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; declare let clientCtx: AWSLambda.ClientContext; @@ -102,11 +103,13 @@ str = apiGwEvtReqCtx.resourcePath; /* API Gateway Event */ strOrNull = apiGwEvt.body; str = apiGwEvt.headers["example"]; +str = apiGwEvt.multiValueHeaders["example"][0]; str = apiGwEvt.httpMethod; bool = apiGwEvt.isBase64Encoded; str = apiGwEvt.path; str = apiGwEvt.pathParameters!["example"]; str = apiGwEvt.queryStringParameters!["example"]; +str = apiGwEvt.multiValueQueryStringParameters!["example"][0]; str = apiGwEvt.stageVariables!["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; str = apiGwEvt.resource; @@ -115,10 +118,12 @@ str = apiGwEvt.resource; str = customAuthorizerEvt.type; str = customAuthorizerEvt.methodArn; strOrUndefined = customAuthorizerEvt.authorizationToken; -str = apiGwEvt.pathParameters!["example"]; -str = apiGwEvt.queryStringParameters!["example"]; -str = apiGwEvt.stageVariables!["example"]; -apiGwEvtReqCtx = apiGwEvt.requestContext; +str = customAuthorizerEvt.headers!["example"]; +str = customAuthorizerEvt.multiValueHeaders!["example"][0]; +str = customAuthorizerEvt.pathParameters!["example"]; +str = customAuthorizerEvt.queryStringParameters!["example"]; +str = customAuthorizerEvt.multiValueQueryStringParameters!["example"][0]; +apiGwEvtReqCtxOpt = customAuthorizerEvt.requestContext; /* DynamoDB Stream Event */ const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { @@ -245,6 +250,9 @@ num = proxyResult.statusCode; proxyResult.headers!["example"] = str; proxyResult.headers!["example"] = bool; proxyResult.headers!["example"] = num; +proxyResult.multiValueHeaders!["example"][0] = str; +proxyResult.multiValueHeaders!["example"][0] = bool; +proxyResult.multiValueHeaders!["example"][0] = num; boolOrUndefined = proxyResult.isBase64Encoded; str = proxyResult.body; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index aa08bf2b03..d9d22f8c65 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -22,6 +22,7 @@ // Louis Larry // Daniel Papukchiev // Oliver Hookins +// Trevor Leach // James Gregory // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -59,11 +60,13 @@ export interface APIGatewayEventRequestContext { export interface APIGatewayProxyEvent { body: string | null; headers: { [name: string]: string }; + multiValueHeaders: { [name: string]: string[] }; httpMethod: string; isBase64Encoded: boolean; path: string; pathParameters: { [name: string]: string } | null; queryStringParameters: { [name: string]: string } | null; + multiValueQueryStringParameters: { [name: string]: string[] } | null; stageVariables: { [name: string]: string } | null; requestContext: APIGatewayEventRequestContext; resource: string; @@ -76,8 +79,10 @@ export interface CustomAuthorizerEvent { methodArn: string; authorizationToken?: string; headers?: { [name: string]: string }; + multiValueHeaders?: { [name: string]: string[] }; pathParameters?: { [name: string]: string } | null; queryStringParameters?: { [name: string]: string } | null; + multiValueQueryStringParameters?: { [name: string]: string[] } | null; requestContext?: APIGatewayEventRequestContext; } @@ -442,6 +447,9 @@ export interface APIGatewayProxyResult { headers?: { [header: string]: boolean | number | string; }; + multiValueHeaders?: { + [header: string]: Array; + }; body: string; isBase64Encoded?: boolean; } diff --git a/types/detective/detective-tests.ts b/types/detective/detective-tests.ts new file mode 100644 index 0000000000..b0c176af03 --- /dev/null +++ b/types/detective/detective-tests.ts @@ -0,0 +1,16 @@ +import detective = require("detective"); + +const opts: detective.Options = { + parse: { + sourceType: "module", + allowImportExportEverywhere: true + } +}; + +detective("content", opts).filter((x) => x && x.length > 0); + +const detectiveFunc: detective.Detective = detective; + +detectiveFunc.find("str").strings.forEach((dep) => { + const b: boolean = dep[0] === '.'; +}); diff --git a/types/detective/index.d.ts b/types/detective/index.d.ts new file mode 100644 index 0000000000..771d88f40c --- /dev/null +++ b/types/detective/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for detective 5.1 +// Project: https://github.com/browserify/detective +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as acorn from "acorn"; + +/** + * Find all calls to require() by walking the AST + */ +declare namespace detective { + interface Detective { + /** + * Give some source body src, return an array of all the require() calls with string arguments. + * The options parameter opts is passed along to detective.find(). + */ + (src: string, opts?: Options): string[]; + /** + * Give some source body 'src', return 'found' DetectiveResults + */ + find(src: string, opts?: Options): DetectiveResults; + } + + interface Options { + /** + * specify a different function name instead of "require" + */ + word?: string; + /** + * when true, populate found.nodes + */ + nodes?: string; + /** + * a function returning whether an AST CallExpression node is a require call + */ + isRequire?: (node: any) => boolean; + /** + * supply options directly to acorn with some support for esprima-style options range and loc + */ + parse?: acorn.Options; + /** + * Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), + * 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial support). This influences + * support for strict mode, the set of reserved words, and support for new syntax features. + * Default is 9. + */ + ecmaVersion?: string | number; + + /** + * If false, using a reserved word will generate an error. Defaults to true for ecmaVersion 3, + * false for higher versions. When given the value "never", reserved words and keywords can + * also not be used as property names (as in Internet Explorer's old parser). + */ + allowReserved?: boolean | "never"; + /** + * By default, a return statement at the top level raises an error. Set this to true to accept such code. + */ + allowReturnOutsideFunction?: boolean; + /** + * By default, import and export declarations can only appear at a program's top level. + * Setting this option to true allows them anywhere where a statement is allowed. + */ + allowImportExportEverywhere?: boolean; + /** + * When this is enabled (off by default), if the code starts with the + * characters #! (as in a shellscript), the first line will be treated as a comment. + */ + allowHashBang?: boolean; + /** + * When true, each node has a loc object attached with start and end subobjects, each of which + * contains the one-based line and zero-based column numbers in {line, column} form. Default is false. + */ + locations?: boolean; + /** + * Nodes have their start and end characters offsets recorded in start and end properties + * (directly on the node, rather than the loc object, which holds line/column data. + * To also add a semi-standardized range property holding a [start, end] array with + * the same numbers, set the ranges option to true. + */ + ranges?: string; + /** + * Indicate the mode the code should be parsed in. Can be either "script" or "module". + * This influences global strict mode and parsing of import and export declarations. + */ + sourceType?: ("script" | "module"); + } + + interface DetectiveResults { + /** + * an array of each string found in a require() + */ + strings: string[]; + /** + * an array of each stringified expression found in a require() call + */ + expressions: string[]; + /** + * (when opts.nodes === true) - an array of AST nodes for each argument found in a require() call + */ + nodes?: any[]; + } +} + +declare var detective: detective.Detective; + +export = detective; diff --git a/types/detective/tsconfig.json b/types/detective/tsconfig.json new file mode 100644 index 0000000000..49cdedb7fd --- /dev/null +++ b/types/detective/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", + "detective-tests.ts" + ] +} \ No newline at end of file diff --git a/types/detective/tslint.json b/types/detective/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detective/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/es6-shim/package.json b/types/es6-shim/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/es6-shim/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/es6-shim/ts3.1/es6-shim-tests.ts b/types/es6-shim/ts3.1/es6-shim-tests.ts new file mode 100644 index 0000000000..87f6fba0e5 --- /dev/null +++ b/types/es6-shim/ts3.1/es6-shim-tests.ts @@ -0,0 +1,234 @@ +declare const require: (module: string) => Object; +if (require !== null) { + require('es6-shim'); +} + +interface Point { x: number; y: number; } +interface Point3D extends Point { z: number; } + +let a: any; +let s: string = ''; +let i: number = 2; +let iOrUndef: number | undefined; +let b: boolean; +let f: () => void = () => {}; +let o: Object; +let r: RegExp = /a/; +let sym: symbol = {} as symbol; +let e: Error = new Error(); +let date: Date; +let key: PropertyKey; +let point: Point = { x: 1, y: 2 }; +let point3d: Point3D = { x: 1, y: 2, z: 3 }; +let point3dOrUndef: Point3D | undefined; +let pointOrUndef: Point | undefined; +let arrayOfPoint: Point[] = []; +let arrayOfPoint3D: Point3D[]; +let arrayOfSymbol: symbol[]; +let arrayOfPropertyKey: PropertyKey[]; +let arrayOfAny: any[]; +let arrayOfStringAny: [string, any][]; +let arrayLikeOfAny: ArrayLike = []; +let iterableOfPoint: IterableShim = []; +let iterableOfStringPoint: IterableShim<[string, Point]> = []; +let iterableOfPointPoint3D: IterableShim<[Point, Point3D]> = []; +let iterableIteratorOfPoint: IterableIteratorShim; +let iterableIteratorOfNumberPoint: IterableIteratorShim<[number, Point]>; +let iterableIteratorOfNumber: IterableIteratorShim; +let iterableIteratorOfString: IterableIteratorShim; +let iterableIteratorOfPointPoint: IterableIteratorShim<[Point, Point]>; +let iterableIteratorOfNode: IterableIteratorShim; +let iterableIteratorOfStringPoint: IterableIteratorShim<[string, Point]>; +let iterableIteratorOfAny: IterableIteratorShim; +let iterableIteratorOfPropertyKey: IterableIteratorShim; +let iterableIteratorOfPropertyKeyPoint: IterableIteratorShim<[PropertyKey, Point]>; +let nodeList: NodeList; +let pd: PropertyDescriptor = {}; +let pdm: PropertyDescriptorMap = {}; +let map: Map = new Map(); +let set: Set = new Set(); +let weakMap: WeakMap = new WeakMap(); +let weakSet: WeakSet = new WeakSet(); +let promiseLikeOfPoint: PromiseLike = Promise.resolve(point); +let promiseLikeOfPoint3D: PromiseLike = Promise.resolve(point3d); +let promiseOfPoint: Promise = Promise.resolve(point); +let promiseOfPoint3D: Promise = Promise.resolve(point3d); +let promiseOfArrayOfPoint: Promise; +let promiseOfVoid: Promise; + +point = Object.assign(point, point); +b = Object.is(point, point); +Object.setPrototypeOf(point, {}); +pointOrUndef = arrayOfPoint.find(p => b); +i = arrayOfPoint.findIndex(p => b); +arrayOfPoint = arrayOfPoint.fill(point, i, arrayOfPoint.length); +arrayOfPoint = arrayOfPoint.copyWithin(i, i, i); +arrayOfPoint = Array.from(arrayOfPoint); +arrayOfPoint = Array.from(iterableOfPoint); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d); +arrayOfPoint3D = Array.from(arrayOfPoint, point => point3d, a); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d); +arrayOfPoint3D = Array.from(iterableOfPoint, point => point3d, a); +arrayOfPoint = Array.of(point, point); +i = s.codePointAt(i); +b = s.includes(s, i); +b = s.endsWith(s, i); +s = s.repeat(i); +b = s.startsWith(s, i); +s = String.fromCodePoint(2 as number, 3 as number); +s = String.raw`abc`; +s = r.flags; +i = Number.EPSILON; +b = Number.isFinite(i); +b = Number.isInteger(i); +b = Number.isNaN(i); +b = Number.isSafeInteger(i); +i = Number.MAX_SAFE_INTEGER; +i = Number.MIN_SAFE_INTEGER; +i = Number.parseFloat(s); +i = Number.parseInt(s); +i = Number.parseInt(s, i); +i = Math.clz32(i); +i = Math.imul(i, i); +i = Math.sign(i); +i = Math.log10(i); +i = Math.log2(i); +i = Math.log1p(i); +i = Math.expm1(i); +i = Math.cosh(i); +i = Math.sinh(i); +i = Math.tanh(i); +i = Math.acosh(i); +i = Math.asinh(i); +i = Math.atanh(i); +i = Math.hypot(i, i); +i = Math.trunc(i); +i = Math.fround(i); +i = Math.cbrt(i); +map.clear(); +map.delete(s); +map.forEach((value: Point, key: string) => { }); +pointOrUndef = map.get(s); +b = map.has(s); +map = map.set(s, point); +i = map.size; +map = new Map(); +map = new Map(iterableOfStringPoint); +set.clear(); +set.delete(point); +set.forEach((value: Point, key: Point) => { }); +b = set.has(point); +set = set.add(point); +i = set.size; +set = new Set(); +set = new Set(iterableOfPoint); +weakMap.delete(point); +point3dOrUndef = weakMap.get(point); +b = weakMap.has(point); +weakMap = weakMap.set(point, point3d); +weakMap = new WeakMap(); +weakMap = new WeakMap(iterableOfPointPoint3D); +weakSet.delete(point); +weakSet = weakSet.add(point); +b = weakSet.has(point); +weakSet = new WeakSet(); +weakSet = new WeakSet(iterableOfPoint); +iterableIteratorOfNumberPoint = arrayOfPoint.entries(); +iterableIteratorOfNumber = arrayOfPoint.keys(); +iterableIteratorOfPoint = arrayOfPoint.values(); +iterableIteratorOfPointPoint = set.entries(); +iterableIteratorOfPoint = set.keys(); +iterableIteratorOfPoint = set.values(); +promiseLikeOfPoint.then((point: Point) => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => point, e => { }); +promiseLikeOfPoint = promiseLikeOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => point3d, e => { }); +promiseLikeOfPoint3D = promiseLikeOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint.then((point: Point) => { }); +promiseOfPoint = promiseOfPoint.then(); +promiseOfPoint = promiseOfPoint.then(p => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => point); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.then(p => point, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseOfPoint, e => { }); +promiseOfPoint = promiseOfPoint.then(p => promiseLikeOfPoint, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => point3d); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => promiseLikeOfPoint3D); +promiseOfPoint3D = promiseOfPoint.then(p => point3d, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseOfPoint3D, e => { }); +promiseOfPoint3D = promiseOfPoint.then(p => promiseLikeOfPoint3D, e => { }); +promiseOfPoint = promiseOfPoint.catch(e => point); +promiseOfPoint = promiseOfPoint.catch(e => promiseOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => promiseLikeOfPoint); +promiseOfPoint = promiseOfPoint.catch(e => { }); +promiseOfPoint3D = promiseOfPoint3D.catch(e => point3d); +promiseOfPoint3D = promiseOfPoint3D.catch(e => promiseOfPoint3D); +promiseOfPoint3D = promiseOfPoint3D.catch(e => promiseLikeOfPoint3D); +promiseOfPoint = new Promise((resolve, reject) => resolve(point)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => resolve(promiseLikeOfPoint)); +promiseOfPoint = new Promise((resolve, reject) => reject(e)); +// To prevent UnhandledPromiseRejectionWarning +promiseOfPoint.catch(() => {}); +promiseOfArrayOfPoint = Promise.all(arrayOfPoint); +promiseOfArrayOfPoint = Promise.all(iterableOfPoint); +promiseOfPoint = Promise.race(arrayOfPoint); +promiseOfPoint = Promise.race(iterableOfPoint); +promiseOfVoid = Promise.resolve(); +promiseOfPoint = Promise.resolve(point3d); +promiseOfPoint = Promise.resolve(promiseOfPoint); +promiseOfPoint = Promise.resolve(promiseLikeOfPoint); +promiseOfVoid = Promise.reject(e); +// To prevent UnhandledPromiseRejectionWarning +promiseOfVoid.catch(() => {}); +promiseOfPoint = Promise.reject(e); +// To prevent UnhandledPromiseRejectionWarning +promiseOfPoint.catch(() => {}); +a = Reflect.apply(f, a, arrayLikeOfAny); +a = Reflect.construct(f, arrayLikeOfAny); +b = Reflect.defineProperty(a, s, pd); +b = Reflect.defineProperty(a, i, pd); +b = Reflect.defineProperty(a, sym, pd); +b = Reflect.deleteProperty(a, s); +b = Reflect.deleteProperty(a, i); +b = Reflect.deleteProperty(a, sym); +iterableIteratorOfAny = Reflect.enumerate(a); +Reflect.get(a, s, a); +Reflect.get(a, i, a); +Reflect.get(a, sym, a); +pd = Reflect.getOwnPropertyDescriptor(a, s); +pd = Reflect.getOwnPropertyDescriptor(a, i); +pd = Reflect.getOwnPropertyDescriptor(a, sym); +a = Reflect.getPrototypeOf(a); +b = Reflect.has(a, s); +b = Reflect.has(a, i); +b = Reflect.has(a, sym); +b = Reflect.isExtensible(a); +arrayOfPropertyKey = Reflect.ownKeys(a); +b = Reflect.preventExtensions(a); +b = Reflect.set(a, s, a, a); +b = Reflect.set(a, i, a, a); +b = Reflect.set(a, sym, a, a); +b = Reflect.setPrototypeOf(a, a); diff --git a/types/es6-shim/ts3.1/index.d.ts b/types/es6-shim/ts3.1/index.d.ts new file mode 100644 index 0000000000..7ed7ef6aba --- /dev/null +++ b/types/es6-shim/ts3.1/index.d.ts @@ -0,0 +1,661 @@ +interface IteratorResult { + done: boolean; + value?: T; +} + +interface IterableShim { + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): Iterator; +} + +interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +interface IterableIteratorShim extends IterableShim, Iterator { + /** + * Shim for an ES6 iterable iterator. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface StringConstructor { + /** + * Return the String value whose elements are, in order, the elements in the List elements. + * If length is 0, the empty string is returned. + */ + fromCodePoint(...codePoints: number[]): string; + + /** + * String.raw is intended for use as a tag function of a Tagged Template String. When called + * as such the first argument will be a well formed template call site object and the rest + * parameter will contain the substitution values. + * @param template A well-formed template string call site representation. + * @param substitutions A set of substitution values. + */ + raw(template: TemplateStringsArray, ...substitutions: any[]): string; +} + +interface String { + /** + * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point + * value of the UTF-16 encoded code point starting at the string element at position pos in + * the String resulting from converting this object to a String. + * If there is no element at that position, the result is undefined. + * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. + */ + codePointAt(pos: number): number; + + /** + * Returns true if searchString appears as a substring of the result of converting this + * object to a String, at one or more positions that are + * greater than or equal to position; otherwise, returns false. + * @param searchString search string + * @param position If position is undefined, 0 is assumed, so as to search all of the String. + */ + includes(searchString: string, position?: number): boolean; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * endPosition – length(this). Otherwise returns false. + */ + endsWith(searchString: string, endPosition?: number): boolean; + + /** + * Returns a String value that is made from count copies appended together. If count is 0, + * T is the empty String is returned. + * @param count number of copies to append + */ + repeat(count: number): string; + + /** + * Returns true if the sequence of elements of searchString converted to a String is the + * same as the corresponding elements of this object (converted to a String) starting at + * position. Otherwise returns false. + */ + startsWith(searchString: string, position?: number): boolean; + + /** + * Returns an HTML anchor element and sets the name attribute to the text value + * @param name + */ + anchor(name: string): string; + + /** Returns a HTML element */ + big(): string; + + /** Returns a HTML element */ + blink(): string; + + /** Returns a HTML element */ + bold(): string; + + /** Returns a HTML element */ + fixed(): string + + /** Returns a HTML element and sets the color attribute value */ + fontcolor(color: string): string + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: number): string; + + /** Returns a HTML element and sets the size attribute value */ + fontsize(size: string): string; + + /** Returns an HTML element */ + italics(): string; + + /** Returns an HTML element and sets the href attribute value */ + link(url: string): string; + + /** Returns a HTML element */ + small(): string; + + /** Returns a HTML element */ + strike(): string; + + /** Returns a HTML element */ + sub(): string; + + /** Returns a HTML element */ + sup(): string; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface ArrayConstructor { + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(iterable: IterableShim, mapfn: (v: T, k: number) => U, thisArg?: any): Array; + + /** + * Creates an array from an array-like object. + * @param arrayLike An array-like object to convert to an array. + */ + from(arrayLike: ArrayLike): Array; + + /** + * Creates an array from an iterable object. + * @param iterable An iterable object to convert to an array. + */ + from(iterable: IterableShim): Array; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: T[]): Array; +} + +interface Array { + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: T, index: number, obj: Array) => boolean, thisArg?: any): T | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: T) => boolean, thisArg?: any): number; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: T, start?: number, end?: number): T[]; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): T[]; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): IterableIteratorShim<[number, T]>; + + /** + * Returns an list of keys in the array + */ + keys(): IterableIteratorShim; + + /** + * Returns an list of values in the array + */ + values(): IterableIteratorShim; + + /** + * Shim for an ES6 iterable. Not intended for direct use by user code. + */ + "_es6-shim iterator_"(): IterableIteratorShim; +} + +interface NumberConstructor { + /** + * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1 + * that is representable as a Number value, which is approximately: + * 2.2204460492503130808472633361816 x 10‍−‍16. + */ + EPSILON: number; + + /** + * Returns true if passed value is finite. + * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * number. Only finite values of the type number, result in true. + * @param number A numeric value. + */ + isFinite(number: number): boolean; + + /** + * Returns true if the value passed is an integer, false otherwise. + * @param number A numeric value. + */ + isInteger(number: number): boolean; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a + * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter + * to a number. Only values of the type number, that are also NaN, result in true. + * @param number A numeric value. + */ + isNaN(number: number): boolean; + + /** + * Returns true if the value passed is a safe integer. + * @param number A numeric value. + */ + isSafeInteger(number: number): boolean; + + /** + * The value of the largest integer n such that n and n + 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1. + */ + MAX_SAFE_INTEGER: number; + + /** + * The value of the smallest integer n such that n and n − 1 are both exactly representable as + * a Number value. + * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)). + */ + MIN_SAFE_INTEGER: number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + parseFloat(string: string): number; + + /** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + parseInt(string: string, radix?: number): number; +} + +interface ObjectConstructor { + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects to copy properties from. + */ + assign(target: any, ...sources: any[]): any; + + /** + * Returns true if the values are the same value, false otherwise. + * @param value1 The first value. + * @param value2 The second value. + */ + is(value1: any, value2: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. Returns the object o. + * @param o The object to change its prototype. + * @param proto The value of the new prototype or null. + * @remarks Requires `__proto__` support. + */ + setPrototypeOf(o: any, proto: any): any; +} + +interface RegExp { + /** + * Returns a string indicating the flags of the regular expression in question. This field is read-only. + * The characters in this string are sequenced and concatenated in the following order: + * + * - "g" for global + * - "i" for ignoreCase + * - "m" for multiline + * - "u" for unicode + * - "y" for sticky + * + * If no flags are set, the value is the empty string. + */ + flags: string; +} + +interface Math { + /** + * Returns the number of leading zero bits in the 32-bit binary representation of a number. + * @param x A numeric expression. + */ + clz32(x: number): number; + + /** + * Returns the result of 32-bit multiplication of two numbers. + * @param x First number + * @param y Second number + */ + imul(x: number, y: number): number; + + /** + * Returns the sign of the x, indicating whether x is positive, negative or zero. + * @param x The numeric expression to test + */ + sign(x: number): number; + + /** + * Returns the base 10 logarithm of a number. + * @param x A numeric expression. + */ + log10(x: number): number; + + /** + * Returns the base 2 logarithm of a number. + * @param x A numeric expression. + */ + log2(x: number): number; + + /** + * Returns the natural logarithm of 1 + x. + * @param x A numeric expression. + */ + log1p(x: number): number; + + /** + * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of + * the natural logarithms). + * @param x A numeric expression. + */ + expm1(x: number): number; + + /** + * Returns the hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cosh(x: number): number; + + /** + * Returns the hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sinh(x: number): number; + + /** + * Returns the hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tanh(x: number): number; + + /** + * Returns the inverse hyperbolic cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + acosh(x: number): number; + + /** + * Returns the inverse hyperbolic sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + asinh(x: number): number; + + /** + * Returns the inverse hyperbolic tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + atanh(x: number): number; + + /** + * Returns the square root of the sum of squares of its arguments. + * @param values Values to compute the square root for. + * If no arguments are passed, the result is +0. + * If there is only one argument, the result is the absolute value. + * If any argument is +Infinity or -Infinity, the result is +Infinity. + * If any argument is NaN, the result is NaN. + * If all arguments are either +0 or −0, the result is +0. + */ + hypot(...values: number[]): number; + + /** + * Returns the integral part of the a numeric expression, x, removing any fractional digits. + * If x is already an integer, the result is x. + * @param x A numeric expression. + */ + trunc(x: number): number; + + /** + * Returns the nearest single precision float representation of a number. + * @param x A numeric expression. + */ + fround(x: number): number; + + /** + * Returns an implementation-dependent approximation to the cube root of number. + * @param x A numeric expression. + */ + cbrt(x: number): number; +} + +interface PromiseLike { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: (reason: any) => T | PromiseLike): Promise; + catch(onrejected?: (reason: any) => void): Promise; +} + +interface PromiseConstructor { + /** + * A reference to the prototype. + */ + prototype: Promise; + + /** + * Creates a new Promise. + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used to resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: IterableShim>): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + race(values: IterableShim>): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * @param value A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): Promise; + + /** + * Creates a new resolved promise . + * @returns A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; + +interface Map { + clear(): void; + delete(key: K): boolean; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): Map; + size: number; + entries(): IterableIteratorShim<[K, V]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; +} + +interface MapConstructor { + new (): Map; + new (iterable: IterableShim<[K, V]>): Map; + prototype: Map; +} + +declare var Map: MapConstructor; + +interface Set { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + size: number; + entries(): IterableIteratorShim<[T, T]>; + keys(): IterableIteratorShim; + values(): IterableIteratorShim; + '_es6-shim iterator_'(): IterableIteratorShim; +} + +interface SetConstructor { + new (): Set; + new (iterable: IterableShim): Set; + prototype: Set; +} + +declare var Set: SetConstructor; + +interface WeakMap { + delete(key: K): boolean; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): WeakMap; +} + +interface WeakMapConstructor { + new (): WeakMap; + new (iterable: IterableShim<[K, V]>): WeakMap; + prototype: WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSet { + add(value: T): WeakSet; + delete(value: T): boolean; + has(value: T): boolean; +} + +interface WeakSetConstructor { + new (): WeakSet; + new (iterable: IterableShim): WeakSet; + prototype: WeakSet; +} + +declare var WeakSet: WeakSetConstructor; + +declare namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): IterableIteratorShim; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; +} + +declare module "es6-shim" { + var String: StringConstructor; + var Array: ArrayConstructor; + var Number: NumberConstructor; + var Math: Math; + var Object: ObjectConstructor; + var Map: MapConstructor; + var Set: SetConstructor; + var WeakMap: WeakMapConstructor; + var WeakSet: WeakSetConstructor; + var Promise: PromiseConstructor; + namespace Reflect { + function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + function construct(target: Function, argumentsList: ArrayLike): any; + function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function enumerate(target: any): Iterator; + function get(target: any, propertyKey: PropertyKey, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function getPrototypeOf(target: any): any; + function has(target: any, propertyKey: PropertyKey): boolean; + function isExtensible(target: any): boolean; + function ownKeys(target: any): Array; + function preventExtensions(target: any): boolean; + function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function setPrototypeOf(target: any, proto: any): boolean; + } +} diff --git a/types/es6-shim/ts3.1/tsconfig.json b/types/es6-shim/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e652a67caa --- /dev/null +++ b/types/es6-shim/ts3.1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "es6-shim-tests.ts" + ] +} diff --git a/types/es6-shim/ts3.1/tslint.json b/types/es6-shim/ts3.1/tslint.json new file mode 100644 index 0000000000..7f26b198d9 --- /dev/null +++ b/types/es6-shim/ts3.1/tslint.json @@ -0,0 +1,19 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "ban-types": false, + "jsdoc-format": false, + "no-inferrable-types": false, + "no-object-literal-type-assertion": false, + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "no-var-keyword": false, + "no-var-requires": false, + "prefer-object-spread": false, + "radix": false, + "semicolon": false, + "unified-signatures": false + } +} diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 09a1e611ea..4b8a69aa93 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -48,6 +48,7 @@ pool.use((conn: Connection) => 'test') pool.acquire() .then((conn: Connection) => { + console.log(pool.isBorrowedResource(conn)); // => true return pool.release(conn); }).then(() => { return pool.acquire(5); diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index e50682ab12..7a446243db 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -24,6 +24,7 @@ export class Pool extends EventEmitter { drain(): PromiseLike; clear(): PromiseLike; use(cb: (resource: T) => U): PromiseLike; + isBorrowedResource(resource: T): boolean; } export interface Factory { diff --git a/types/makeup-floating-label/index.d.ts b/types/makeup-floating-label/index.d.ts new file mode 100644 index 0000000000..7b35349554 --- /dev/null +++ b/types/makeup-floating-label/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for makeup-floating-label 0.0 +// Project: https://github.com/makeup-js/makeup-floating-label#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +declare class FloatingLabel { + constructor(el: any, userOptions?: any); + refresh(): void; +} + +export = FloatingLabel; diff --git a/types/makeup-floating-label/makeup-floating-label-tests.ts b/types/makeup-floating-label/makeup-floating-label-tests.ts new file mode 100644 index 0000000000..3883e4135f --- /dev/null +++ b/types/makeup-floating-label/makeup-floating-label-tests.ts @@ -0,0 +1,9 @@ +import FloatingLabel = require('makeup-floating-label'); + +const widgetEls = document.querySelectorAll('.floating-label'); + +widgetEls.forEach((el: Element) => { + const widget = new FloatingLabel(el); + + widget.refresh(); +}); diff --git a/types/makeup-floating-label/tsconfig.json b/types/makeup-floating-label/tsconfig.json new file mode 100644 index 0000000000..c7fed3a8c4 --- /dev/null +++ b/types/makeup-floating-label/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom", + "dom.iterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "makeup-floating-label-tests.ts" + ] +} diff --git a/types/makeup-floating-label/tslint.json b/types/makeup-floating-label/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-floating-label/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 7d31585d32..79b5c553fb 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1556,7 +1556,7 @@ declare module "mongoose" { * been using Query, we set it as an alias of DocumentQuery. */ class Query extends DocumentQuery { } - class DocumentQuery extends mquery { + class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. * Only use $where when you have a condition that cannot be met using other MongoDB @@ -1636,8 +1636,8 @@ declare module "mongoose" { * Specifying this query as a count query. Passing a callback executes the query. * @param criteria mongodb selector */ - count(callback?: (err: any, count: number) => void): Query; - count(criteria: any, callback?: (err: any, count: number) => void): Query; + count(callback?: (err: any, count: number) => void): Query & QueryHelpers; + count(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Specifies this query as a `countDocuments()` query. Behaves like `count()`, @@ -1658,8 +1658,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -1671,8 +1671,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a @@ -1681,10 +1681,10 @@ declare module "mongoose" { cursor(options?: any): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ - distinct(callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(callback?: (err: any, res: any[]) => void): Query & QueryHelpers; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, criteria: any | Query, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** Specifies an $elemMatch condition */ elemMatch(criteria: (elem: Query) => void): this; @@ -1708,9 +1708,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; find(criteria: any, - callback?: (err: any, res: DocType[]) => void): DocumentQuery; + callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; /** * Declares the query a findOne operation. When executed, the first found document is @@ -1719,36 +1719,36 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; + findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; findOne(criteria: any, - callback?: (err: any, res: DocType | null) => void): DocumentQuery; + callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1806,7 +1806,7 @@ declare module "mongoose" { * getters/setters or other Mongoose magic applied. * @param bool defaults to true */ - lean(bool?: boolean): Query; + lean(bool?: boolean): Query & QueryHelpers; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; @@ -1930,8 +1930,8 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: any | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query & QueryHelpers; + remove(criteria: any | Query, callback?: (err: any) => void): Query & QueryHelpers; /** Specifies which document fields to include or exclude (also known as the query "projection") */ select(arg: string | any): this; @@ -2009,20 +2009,20 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): new (...args: any[]) => Query; - toConstructor(): new (...args: any[]) => DocumentQuery; + toConstructor(): new (...args: any[]) => Query & QueryHelpers; + toConstructor(): new (...args: any[]) => DocumentQuery & QueryHelpers; /** * Declare and/or execute this query as an update() operation. * All paths passed that are not $atomic operations will become $set ops. * @param doc the update command */ - update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: any, callback?: (err: any, affectedRows: number) => void): Query; + update(callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; + update(doc: any, callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, options: QueryUpdateOptions, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; /** Specifies a path for use with chaining. */ where(path?: string | any, val?: any): this; @@ -2608,7 +2608,7 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#model-js */ export var Model: Model; - interface Model extends NodeJS.EventEmitter, ModelProperties { + interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2658,11 +2658,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: any | string | number, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; model(name: string): Model; @@ -2670,7 +2670,7 @@ declare module "mongoose" { * Creates a Query and specifies a $where condition. * @param argument is a javascript string or anonymous function */ - $where(argument: string | Function): DocumentQuery; + $where(argument: string | Function): DocumentQuery & QueryHelpers; /** * Performs aggregations on the models collection. @@ -2682,7 +2682,7 @@ declare module "mongoose" { aggregate(aggregations: any[], cb: Function): Promise; /** Counts number of matching documents in a database collection. */ - count(conditions: any, callback?: (err: any, count: number) => void): Query; + count(conditions: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Counts number of documents matching `criteria` in a database collection. @@ -2696,8 +2696,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -2709,8 +2709,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Shortcut for saving one or more documents to the database. MyModel.create(docs) @@ -2730,9 +2730,9 @@ declare module "mongoose" { discriminator(name: string, schema: Schema): Model; /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, conditions: any, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** * Sends ensureIndex commands to mongo for each index declared in the schema. @@ -2752,12 +2752,12 @@ declare module "mongoose" { * Finds documents. * @param projection optional fields to return */ - find(callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery; + find(callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; + find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, options?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; @@ -2768,15 +2768,15 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): DocumentQuery; + findByIdAndRemove(): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** @@ -2788,28 +2788,28 @@ declare module "mongoose" { */ findByIdAndDelete(): DocumentQuery; findByIdAndDelete(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndDelete(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): DocumentQuery; + findByIdAndUpdate(): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: { upsert: true, new: true } & ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Finds one document. @@ -2817,20 +2817,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): DocumentQuery; + findOneAndRemove(): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2841,16 +2841,16 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findOneAndDelete command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndDelete(): DocumentQuery; + findOneAndDelete(): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2867,7 +2867,7 @@ declare module "mongoose" { rawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean|string; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. @@ -2875,15 +2875,15 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): DocumentQuery; + findOneAndUpdate(): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: { upsert: true, new: true } & ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Implements $geoSearch functionality for Mongoose @@ -2900,7 +2900,7 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: T[]) => void): DocumentQuery; + }, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; /** * Shortcut for creating a new Document from existing raw data, @@ -2960,35 +2960,35 @@ declare module "mongoose" { callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ - remove(conditions: any, callback?: (err: any) => void): Query; - deleteOne(conditions: any, callback?: (err: any) => void): Query; - deleteMany(conditions: any, callback?: (err: any) => void): Query; + remove(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteOne(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteMany(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; /** * Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set). * This function triggers the following middleware: replaceOne */ - replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query; + replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** * Updates documents in the database without returning them. * All update values are cast to their appropriate SchemaTypes before being sent. */ update(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; update(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: any): Query; + where(path: string, val?: any): Query & QueryHelpers; } interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 78f23372cb..a57d3d085a 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -2000,3 +2000,29 @@ new mongoose.Schema({ name: String }, { wtimeout: 1000 } }); + +/* Query helpers: https://mongoosejs.com/docs/guide.html#query-helpers */ + +interface Animal2 extends mongoose.Document { + name: string; + type: string; + tags: string[]; +} +var animal2Schema = new mongoose.Schema({ + name: String, + type: String, + tags: { type: [String], index: true } // field level +}); +let animal2QueryHelpers = { + byName>(this: Q, name: string) { + return this.where({ name: new RegExp(name, 'i') }); + } +}; +animal2Schema.query = animal2QueryHelpers; +var Animal2 = mongoose.model>('Animal', animal2Schema); +Animal2.find().byName('fido').exec(function(err, animals) { + console.log(animals); +}); +Animal2.findOne().byName('fido').exec(function(err, animal) { + console.log(animal); +}); diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 51f6c8a3fc..98e296cfd9 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -8648,7 +8648,7 @@ declare namespace Office { * * In addition to this signature, this method also has the following signature: * - * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` + * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` * * @param coercionType The format for the returned body. * @param options Optional. An object literal that contains one or more of the following properties: @@ -8656,7 +8656,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8677,7 +8677,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Gets a value that indicates whether the content is in HTML or text format. @@ -10403,13 +10403,13 @@ declare namespace Office { * * `saveAsync(options: Office.AsyncContextOptions): void;` * - * `saveAsync(callback: (result: AsyncResult) => void): void;` + * `saveAsync(callback: (result: AsyncResult) => void): void;` * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Asynchronously saves an item. * @@ -10510,7 +10510,7 @@ declare namespace Office { * * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(callback: (result: AsyncResult) => void): void; + saveAsync(callback: (result: AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 75f045af01..4392d09ae9 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for pino 5.6 +// Type definitions for pino 5.8 // Project: https://github.com/pinojs/pino.git // Definitions by: Peter Snider // BendingBender // Christian Rackerseder // GP +// Alex Ferrando // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -12,6 +13,7 @@ import * as stream from 'stream'; import * as http from 'http'; import { EventEmitter } from 'events'; +import SonicBoom = require('sonic-boom'); export = P; @@ -20,7 +22,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; /** * @param [options]: an options object @@ -28,7 +30,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; declare namespace P { /** @@ -75,11 +77,6 @@ declare namespace P { * The default time function for Pino. Returns a string like `,"time":1493426328206`. */ epochTime: TimeFn; - /** - * Returns an ISO formatted string like `,"time":"2017-04-29T004749.354Z"`. It is highly recommended that you avoid this function. - * It incurs a significant performance penalty. - */ - slowTime: TimeFn; /** * Returns an empty string. This function is used when the `timestamp` option is set to `false`. */ @@ -87,12 +84,19 @@ declare namespace P { }; /** - * Provides access to the CLI log prettifier as an API. - * This can also be enabled via the constructor by setting the `prettyPrint` option to either `true` or a configuration object described in this section. - * @param [options]: an options object - * @returns A transform stream to be used as input for the constructor. + * Create a Pino Destination instance: a stream-like object with significantly more throughput (over 30%) than a standard Node.js stream. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function */ - function pretty(options?: PrettyOptions): stream.Transform; + function destination(fileDescriptor?: string | number): SonicBoom; + + /** + * Create an extreme mode destination. This yields an additional 60% performance boost. + * There are trade-offs that should be understood before usage. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function + */ + function extreme(fileDescriptor?: string | number): SonicBoom; interface LevelMapping { /** @@ -128,19 +132,6 @@ declare namespace P { * Caution: any sort of formatted time will significantly slow down Pino's performance. */ timestamp?: TimeFn | false; - /** - * @deprecated - * This option is scheduled to be removed in Pino 5.0.0. Use `timestamp: pino.stdTimeFunctions.slowTime` instead. - * Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). - * WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. - * The pino -t command will do this for you (see CLI). Default: `false`. - */ - slowtime?: boolean; - /** - * Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). - * There are trade-off's should be understood before usage. See Extreme mode explained. Default: `false`. - */ - extreme?: boolean; /** * One of the supported levels or `silent` to disable logging. Any other value defines a custom level and * requires supplying a level value via `levelVal`. Default: 'info'. diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index cec8f658fb..609cac121f 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -22,15 +22,6 @@ const log2: pino.Logger = pino({ } }); -const pretty = pino.pretty(); -pretty.pipe(process.stdout); -const log3 = pino({ - name: 'app', - safe: true -}, pretty); -log3.child({widget: 'foo'}).info('hello'); -log3.child({widget: 'bar'}).warn('hello 2'); - pino({ browser: { write(o) { diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index ca81b0d908..2e1cfb902b 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React Router 4.0 +// Type definitions for React Router 4.4 // Project: https://github.com/ReactTraining/react-router // Definitions by: Sergey Buturlakin // Yuichi Murata @@ -18,6 +18,7 @@ // Rahul Raina // Maksim Sharipov // Duong Tran +// Ben Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -76,7 +77,7 @@ export interface RouteProps { component?: React.ComponentType> | React.ComponentType; render?: ((props: RouteComponentProps) => React.ReactNode); children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; - path?: string; + path?: string | string[]; exact?: boolean; sensitive?: boolean; strict?: boolean; diff --git a/types/react-router/test/Switch.tsx b/types/react-router/test/Switch.tsx index fe959504ce..03d65125f0 100644 --- a/types/react-router/test/Switch.tsx +++ b/types/react-router/test/Switch.tsx @@ -4,6 +4,7 @@ import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom'; const Home = () =>

Home

; const About = () =>

About

; const User = () =>

User

; +const Contact = () =>

Contact

; const SwitchTest = () => ( @@ -12,7 +13,8 @@ const SwitchTest = () => ( {[ , - + , + ]} diff --git a/types/sonic-boom/index.d.ts b/types/sonic-boom/index.d.ts new file mode 100644 index 0000000000..292770bd0d --- /dev/null +++ b/types/sonic-boom/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for sonic-boom 0.6 +// Project: https://github.com/mcollina/sonic-boom.git +// Definitions by: Alex Ferrando +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events'; + +export = SonicBoom; + +declare class SonicBoom extends EventEmitter { + /** + * @param [fileDescriptor] File path or numerical file descriptor + * relative protocol is enabled. Default: process.stdout + * @returns a new sonic-boom instance + */ + constructor(fileDescriptor: string | number) + + /** + * Writes the string to the file. It will return false to signal the producer to slow down. + */ + write(string: string): void; + + /** + * Writes the current buffer to the file if a write was not in progress. + * Do nothing if minLength is zero or if it is already writing. + */ + flush(): void; + + /** + * Reopen the file in place, useful for log rotation. + */ + reopen(file: string): void; + + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + + /** + * Closes the stream, the data will be flushed down asynchronously + */ + end(): void; + + /** + * Closes the stream immediately, the data is not flushed. + */ + destroy(): void; +} diff --git a/types/sonic-boom/sonic-boom-tests.ts b/types/sonic-boom/sonic-boom-tests.ts new file mode 100644 index 0000000000..a3beb06d0c --- /dev/null +++ b/types/sonic-boom/sonic-boom-tests.ts @@ -0,0 +1,12 @@ +import SonicBoom = require('sonic-boom'); +const sonic = new SonicBoom(1); + +sonic.write('hello sonic\n'); + +sonic.flush(); + +sonic.flushSync(); + +sonic.end(); + +sonic.destroy(); diff --git a/types/sonic-boom/tsconfig.json b/types/sonic-boom/tsconfig.json new file mode 100644 index 0000000000..46c62493b0 --- /dev/null +++ b/types/sonic-boom/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", + "sonic-boom-tests.ts" + ] +} diff --git a/types/sonic-boom/tslint.json b/types/sonic-boom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sonic-boom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/string-replace-webpack-plugin/index.d.ts b/types/string-replace-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..b62c43e448 --- /dev/null +++ b/types/string-replace-webpack-plugin/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for string-replace-webpack-plugin 0.1 +// Project: https://github.com/jamesandersen/string-replace-webpack-plugin +// Definitions by: Rongjian Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin, RuleSetUse } from "webpack"; + +export = StringReplacePlugin; + +declare class StringReplacePlugin extends Plugin { + static replace( + options: StringReplacePlugin.Options, + /** + * loaders to follow the replacement + */ + nextLoaders?: string + ): RuleSetUse; + static replace( + /** + * loaders to apply prior to the replacement + */ + prevLoaders: string, + options: StringReplacePlugin.Options, + /** + * loaders to follow the replacement + */ + nextLoaders?: string + ): RuleSetUse; +} + +declare namespace StringReplacePlugin { + interface Options { + replacements: ReplacementItem[]; + } + + interface ReplacementItem { + /** + * a regex to match against the file contents + */ + pattern: RegExp; + /** + * an ECMAScript string replacement function + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter + */ + replacement: (substring: string, ...args: any[]) => string; + } +} diff --git a/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts b/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts new file mode 100644 index 0000000000..b4b0d5304a --- /dev/null +++ b/types/string-replace-webpack-plugin/string-replace-webpack-plugin-tests.ts @@ -0,0 +1,17 @@ +import StringReplacePlugin = require('string-replace-webpack-plugin'); + +StringReplacePlugin.replace('babel-loader', { + replacements: [ + { + // Taken from: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter + pattern: /([^\d]*)(\d*)([^\w]*)/, + replacement: (match, p1, p2, p3, offset, string) => { + // p1 is nondigits, p2 digits, and p3 non-alphanumerics + return [p1, p2, p3].join(' - '); + } + } + ] +}); + +new StringReplacePlugin(); diff --git a/types/string-replace-webpack-plugin/tsconfig.json b/types/string-replace-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..0c92ee657b --- /dev/null +++ b/types/string-replace-webpack-plugin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "string-replace-webpack-plugin-tests.ts"] +} diff --git a/types/string-replace-webpack-plugin/tslint.json b/types/string-replace-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/string-replace-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/styled-system/dist/styles.d.ts b/types/styled-system/dist/styles.d.ts index ab045b3b4b..5851c51f79 100644 --- a/types/styled-system/dist/styles.d.ts +++ b/types/styled-system/dist/styles.d.ts @@ -192,7 +192,7 @@ export interface RatioProps { export function ratio(...args: any[]): any; -export type VerticleAlignValue = +export type VerticalAlignValue = | "baseline" | "sub" | "super" @@ -203,13 +203,13 @@ export type VerticleAlignValue = | "bottom" | string | number; -export type ResponsiveVerticleAlignValue = ResponsiveValue; +export type ResponsiveVerticalAlignValue = ResponsiveValue; -export interface VerticleAlignProps { - verticalAlign?: ResponsiveVerticleAlignValue; +export interface VerticalAlignProps { + verticalAlign?: ResponsiveVerticalAlignValue; } -export function verticleAlign(...args: any[]): any; +export function verticalAlign(...args: any[]): any; /** * Flexbox diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index d9c386242c..2511fbb99c 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -7,6 +7,7 @@ // Eloy Durán // Matthieu Vachon // Adam Lavin +// Joachim Schuler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index c0f9ba9ded..756dd0c039 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -121,6 +121,8 @@ import { VariantArgs, ButtonStyleProps, MixedProps, + VerticalAlignProps, + verticalAlign } from "styled-system"; // tslint:disable-next-line:strict-export-declare-modifiers @@ -166,7 +168,8 @@ interface BoxProps BackgroundSizeProps, ColorStyleProps, TextStyleProps, - MixedProps { + MixedProps, + VerticalAlignProps { boxStyle?: string; } const Box: React.ComponentType = styled` @@ -213,6 +216,7 @@ const Box: React.ComponentType = styled` ${textStyle} ${colorStyle} ${mixed} + ${verticalAlign} `; Box.defaultProps = { @@ -449,6 +453,8 @@ const test = () => ( backgroundPosition="center" backgroundRepeat="repeat-x" /> + // verticalAlign + diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 7243ec2a10..9e77516978 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for Swiper 4.2 // Project: https://github.com/nolimits4web/Swiper -// Definitions by: Sebastián Galiano , Luca Trazzi , Eugene Matseruk , Luiz M. +// Definitions by: Sebastián Galiano +// Luca Trazzi +// Eugene Matseruk +// Luiz M. +// Justin Abene // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -1047,7 +1051,7 @@ export default class Swiper { * @param runCallbacks Set it to false (by default it is true) and transition will * not produce transition events. */ - slideNext(speed: number, runCallbacks: boolean): void; + slideNext(speed?: number, runCallbacks?: boolean): void; /** * Run transition to previous slide. diff --git a/types/tern/index.d.ts b/types/tern/index.d.ts new file mode 100644 index 0000000000..ef01c0e289 --- /dev/null +++ b/types/tern/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for tern 0.22 +// Project: https://github.com/ternjs/tern +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// IMPORTANT Note: These type definitions adhere strictly to the official documentation, +// which does not seem to match the implementation exactly in some places. +// As a result, these type definitions may lack some parts of the API that are actually exposed. +// The type definitions are at a point where they are usable and match the documentation, +// thus if you want to use undocumented APIs, you should extends these definitions with +// ambient declaration merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html + +export * from "./lib/tern"; +export * from "./lib/infer"; diff --git a/types/tern/lib/infer/index.d.ts b/types/tern/lib/infer/index.d.ts new file mode 100644 index 0000000000..58e83ea1c7 --- /dev/null +++ b/types/tern/lib/infer/index.d.ts @@ -0,0 +1,218 @@ +import * as ESTree from "estree"; +export { }; + +// #### Context #### +interface ContextConstructor { + new(defs: any[]): Context; +} +export const Context: ContextConstructor; +export interface Context { + topScope: Scope; + /** The primitive number type. */ + num: Type; + /** The primitive string type. */ + str: Type; + /** The primitive boolean type. */ + bool: Type; +} +export function cx(): Context; +export function withContext(context: Context, f: () => void): void; + +// #### Analysis #### +/** Parse a piece of code for use by Tern. Will automatically fall back to the error-tolerant parser if the regular parser can’t parse the code. */ +export function parse(text: string, options?: {}): ESTree.Program; +/** + * Analyze a syntax tree. `name` will be used to set the origin of types, properties, and variables produced by this code. + * The optional `scope` argument can be used to specify a scope in which the code should be analyzed. + * It will default to the top-level scope. + */ +export function analyze(ast: ESTree.Program, name: string, scope?: Scope): void; +/** + * Purges the types that have one of the origins given from the context. `start` and `end` can be given to only purge + * types that occurred in the source code between those offsets. This is not entirely precise — the state of the + * context won’t be back where it was before the file was analyzed — but it prevents most of the + * noticeable inaccuracies that re-analysis tends to produce. + */ +export function purgeTypes(origins: string[], start?: number, end?: number): void; +/** + * Cleaning up variables is slightly trickier than cleaning up types. This does a first pass over the given scope, + * and marks variables defined by the given origins. This is indended to be followed by a call to `analyze` and then a call to `purgeMarkedVariables`. + */ +export function markVariablesDefinedBy(scope: Scope, origins: string[], start?: number, end?: number): void; +/** Purges variables that were marked by a call to markVariablesDefinedBy and not re-defined in the meantime. */ +export function purgeMarkedVariables(): void; + +// #### Types #### +interface ObjConstructor { + new(proto: object | true | null, name?: string): Obj; +} +/** Constructor for the type that represents JavaScript objects. `proto` may be another object, or `true` as a short-hand for `Object.prototype`, or `null` for prototype-less objects. */ +export const Obj: ObjConstructor; +export interface Obj extends Type { + /** The prototype of the object, or null. */ + proto: any; + /** An object mapping the object’s known properties to AVals. Don’t manipulate this directly (ever), only use it if you have to iterate over the properties. */ + props: Readonly<{ + [key: string]: AVal; + }>; + /** Looks up the AVal associated with the given property, or returns null if it doesn’t exist. */ + hasProp(prop: string): AVal | null; + /** Looks up the given property, or defines it if it did not yet exist (in which case it will be associated with the given AST node). */ + defProp(prop: string, originNode?: ESTree.Node): AVal; +} + +interface FnConstructor { + new(name: string | undefined, self: AVal, args: AVal[], argNames: string[], retval: AVal): Fn; +} +/** Constructor for the type that implements functions. Inherits from `Obj`. The `AVal` types are used to track the input and output types of the function. */ +export const Fn: FnConstructor; +export type Fn = Obj; + +interface ArrConstructor { + /** Constructor that creates an array type with the given content type. */ + new(contentType: AVal): Arr; +} +export const Arr: ArrConstructor; +export type Arr = Obj; + +export interface Type extends AVal { + /** The name of the type, if any. */ + name: string; + /** The origin file of the type. */ + origin: string; + /** + * The syntax node that defined the type. Only present for object and function types, + * and even for those it may be missing (if the type was created by a type definition file, + * or synthesized in some other way). + */ + originNode?: ESTree.Node; + /** Return a string that describes the type. maxDepth indicates the depth to which inner types should be shown. */ + toString(maxDepth: number): string; + /** Get an `AVal` that represents the named property of this type. */ + getProp(prop: string): AVal; + /** Call the given function for all properties of the object, including properties that are added in the future. */ + forAllProps(f: (prop: string, val: AVal, local: boolean) => void): void; +} + +// #### Abstract Values #### + +interface AValConstructor { + new(): AVal; +} +export const AVal: AValConstructor; +export interface AVal { + /** + * Add a type to this abstract value. If the type is already in there, + * this is a no-op. weight can be given to give this type a non-default + * weight, which is mostly useful when adding a provisionary type that + * should be overridden later if a real type is found. The default weight + * is 100, and passing a weight lower than that will make the type + * assignment “weak”. + */ + addType(type: Type, weight?: number): void; + /** + * Sets this AVal to propagate all types it receives to the given + * constraint. This is the mechanism by which types are propagated + * through the type graph. + */ + propagate(target: Constraint): void; + /** Queries whether the AVal _currently_ holds the given type. */ + hasType(type: Type): boolean; + /** Queries whether the AVal is empty. */ + isEmpty(): boolean; + /** + * Asks the abstract value for its current type. May return `null` + * when there is no type, or conflicting types are present. When + * `guess` is true or not given, an empty AVal will try to use + * heuristics based on its propagation edges to guess a type. + */ + getType(guess?: boolean): Type | null; + /** + * Asks the AVal if it contains a function type. Useful when + * you aren’t interested in other kinds of types. + */ + getFunctionType(): Type | undefined; + /** + * Abstract values that are used to represent variables + * or properties will have, when possible, an `originNode` + * property pointing to an AST node. + */ + originNode?: ESTree.Node; +} + +export const ANull: ANull; +export interface ANull extends AVal { + addType(): void; + propagate(target: never): void; + hasType(): false; + isEmpty(): true; + getFunctionType(): undefined; + getType(): null; + originNode: undefined; +} + +// #### Constraints #### +interface ConstraintConstructor { + new(methods: { [key: string]: any }): { new(): Constraint }; +} +/** + * This is a constructor-constructor for constraints. It’ll create a + * constructor with all the given methods copied into its prototype, + * which will run its construct method on its arguments when instantiated. + */ +export const constraint: ConstraintConstructor; +export interface Constraint extends AVal { + /** May return a type that `getType` can use to “guess” its type based on the fact that it propagates to this constraint. */ + typeHint?(): Type | undefined; + /** May return a string when this constraint is indicative of the presence of a specific property in the source AVal. */ + propHint?(): string | undefined; +} + +// #### Scopes #### +interface ScopeConstructor { + new(parent?: Scope): Scope; +} +export const Scope: ScopeConstructor; +export interface Scope extends Obj { + /** + * Ensures that this scope or some scope above it has a property by the given name + * (defining it in the top scope if it is missing), and, if the property doesn’t + * already have an `originNode`, assigns the given node to it. + */ + defVar(name: string, originNode: ESTree.Node): AVal; +} + +// #### Utilities #### +/** + * Searches the given syntax tree for an expression that ends at the given `end` offset and, + * if `start` is given, starts at the given start offset. `scope` can be given to override the + * outer scope, which defaults to the context’s top scope. Will return a `{node, state}` + * object if successful, where `node` is AST node, and `state` is the scope at that point. + * Returns `null` if unsuccessful. + */ +export function findExpressionAt(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** + * Similar to `findExpressionAt`, except that it will return the innermost expression + * node that spans the given range, rather than only exact matches. + */ +export function findExpressionAround(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** Similar to `findExpressionAround`, except that it use the same AST walker as `findExpressionAt`. */ +export function findClosestExpression(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null; +/** Determine an expression for the given node and scope (as returned by the functions above). Will return an `AVal` or plain `Type`. */ +export function expressionType(expr: { node: ESTree.Node, state: Scope }): AVal | Type; +/** Find the scope at a given position in the syntax tree. The `scope` parameter can be used to override the scope used for code that isn’t wrapped in any function. */ +export function scopeAt(ast: ESTree.Program, pos: number, scope?: Scope): Scope; +/** + * Will traverse the given syntax tree, using `scope` as the starting scope, looking for references to variable `name` that + * resolve to scope `refScope`, and call `f` with the node of the reference and its local scope for each of them. + */ +export function findRefs(ast: ESTree.Program, scope: Scope, name: string, refScope: Scope, f: (Node: ESTree.Node, Scope: Scope) => void): void; +/** + * Analogous to `findRefs`, but used to look for references to a specific property instead. Whereas `findRefs` + * is precise, this is dependent on type inference, and thus can not be relied on to be precise. + */ +export function findPropRefs(ast: ESTree.Program, scope: Scope, objType: Obj, propName: string, f: (Node: ESTree.Node) => void): void; +/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `didGuess` tests whether the guessing flag is set. */ +export function didGuess(): boolean; +/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `resetGuessing` resets the guessing flag. */ +export function resetGuessing(val?: boolean): void; diff --git a/types/tern/lib/tern/index.d.ts b/types/tern/lib/tern/index.d.ts new file mode 100644 index 0000000000..ee51a79119 --- /dev/null +++ b/types/tern/lib/tern/index.d.ts @@ -0,0 +1,500 @@ +import * as ESTree from "estree"; +import { Scope, Type } from "../infer"; + +export { }; + +// #### Programming interface #### +export type ConstructorOptions = CtorOptions & (SyncConstructorOptions | ASyncConstructorOptions); + +interface CtorOptions { + /** The definition objects to load into the server’s environment. */ + defs?: Def[]; + /** The ECMAScript version to parse. Should be either 5 or 6. Default is 6. */ + ecmaVersion?: 5 | 6; + /** Indicates the maximum amount of milliseconds to wait for an asynchronous getFile before giving up on it. Defaults to 1000. */ + fetchTimeout?: number; + /** Specifies the set of plugins that the server should load. The property names of the object name the plugins, and their values hold options that will be passed to them. */ + plugins?: { [key: string]: object }; +} + +interface SyncConstructorOptions { + /** Indicates whether `getFile` is asynchronous. Default is `false`. */ + async?: false; + /** + * Provides a way for the server to try and fetch the content of files. + * Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or + * a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument, + * and the `content` string (if no error) as the second. + */ + getFile?(filename: string): string; +} + +interface ASyncConstructorOptions { + /** Indicates whether `getFile` is asynchronous. Default is `false`. */ + async: true; + /** + * Provides a way for the server to try and fetch the content of files. + * Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or + * a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument, + * and the `content` string (if no error) as the second. + */ + getFile?(filename: string, callback: (error: Error | undefined, content?: string) => void): void; +} + +interface TernConstructor { + new(options?: ConstructorOptions): Server; +} + +export const Server: TernConstructor; + +export interface Server { + /** + * Add a set of type definitions to the server. If `atFront` is true, they will be added before all other + * existing definitions. Otherwise, they are added at the back. + */ + addDefs(defs: Def[], atFront?: boolean): void; + + /** + * Register a file with the server. Note that files can also be included in requests. When using this + * to automatically load a dependency, specify the name of the file (as Tern knows it) as the third + * argument. That way, the file is counted towards the dependency budget of the root of its dependency graph. + */ + addFile(name: string, text?: string, parent?: string): void; + + /** Unregister a file. */ + delFile(name: string): void; + + /** + * Delete a set of type definitions from the server, by providing the name, taken from + * `defs[!name]` property from the definitions. If that property is not available in the + * current type definitions, it can’t be removed. + */ + deleteDefs(name: string): void; + + /** Forces all files to be fetched an analyzed, and then calls the callback function. */ + flush(callback: () => void): void; + + /** Load a server plugin (or don’t do anything, if the plugin is already loaded). */ + loadPlugin(name: string, options: object): void; + + /** Unregister an event handler. */ + off(eventType: K, handler: Events[K]): void; + + /** Register an event handler for the named type of event. */ + on(eventType: K, handler: Events[K]): void; + + /** + * Perform a request. `doc` is a (parsed) JSON document as described in the protocol documentation. + * The `callback` function will be called when the request completes. If an `error` occurred, + * it will be passed as a first argument. Otherwise, the `response` (parsed) JSON object will be passed as second argument. + * + * When the server hasn’t been configured to be asynchronous, the callback will be called before request returns. + */ + request( + doc: D & { query?: Q }, + callback: ( + error: Error | undefined, + response: (D extends { query: undefined } ? {} : D extends { query: Query } ? QueryResult : {}) | undefined + ) => void + ): void; +} + +// #### JSON Protocol #### + +type QueryResult = QueryRegistry[Q["type"]]["result"]; + +type Query = QueryRegistry[keyof QueryRegistry]["query"]; + +export interface QueryRegistry { + completions: { + query: CompletionsQuery, + result: CompletionsQueryResult + }; + type: { + query: TypeQuery, + result: TypeQueryResult + }; + definition: { + query: DefinitionQuery, + result: DefinitionQueryResult + }; + documentation: { + query: DocumentationQuery; + result: DocumentationQueryResult; + }; + refs: { + query: RefsQuery; + result: RefsQueryResult; + }; + rename: { + query: RenameQuery, + result: RenameQueryResult + }; + properties: { + query: PropertiesQuery, + result: PropertiesQueryResult + }; + files: { + query: FilesQuery, + result: FilesQueryResult + }; +} + +export interface Def { + [key: string]: string | Def; +} + +export interface Document { + query?: Query; + files?: File[]; + timeout?: number; +} + +export interface File { + name: string; + text: string; + scope: Scope; + ast: ESTree.Program; + type?: "full" | "part" | "delete"; +} + +export interface BaseQuery { + type: string; + lineCharPositions?: boolean; + docFormat?: "full"; +} + +interface Position { + ch: number; + line: number; +} + +/** Asks the server for a set of completions at the given point. */ +export interface CompletionsQuery extends BaseQuery { + /** Asks the server for a set of completions at the given point. */ + type: "completions"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location to complete at. */ + end: number | Position; + /** Whether to include the types of the completions in the result data. Default `false` */ + types?: boolean; + /** Whether to include the distance (in scopes for variables, in prototypes for properties) between the completions and the origin position in the result data. Default `false` */ + depths?: boolean; + /** Whether to include documentation strings in the result data. Default `false` */ + docs?: boolean; + /** Whether to include urls in the result data. Default `false` */ + urls?: boolean; + /** Whether to include origin files (if found) in the result data. Default `false` */ + origins?: boolean; + /** When on, only completions that match the current word at the given point will be returned. Turn this off to get all results, so that you can filter on the client side. Default `true` */ + filter?: boolean; + /** Whether to use a case-insensitive compare between the current word and potential completions. Default `false` */ + caseInsensitive?: boolean; + /** When completing a property and no completions are found, Tern will use some heuristics to try and return some properties anyway. Set this to `false` to turn that off. Default `true` */ + guess?: boolean; + /** Determines whether the result set will be sorted. Default `true` */ + sort?: boolean; + /** + * When disabled, only the text before the given position is considered part of the word. When enabled (the default), + * the whole variable name that the cursor is on will be included. Default `true` + */ + expandWordForward?: boolean; + /** Whether to ignore the properties of `Object.prototype` unless they have been spelled out by at least two characters. Default `true` */ + omitObjectPrototype?: boolean; + /** Whether to include JavaScript keywords when completing something that is not a property. Default `false` */ + includeKeywords?: boolean; + /** If completions should be returned when inside a literal. Default `true` */ + inLiteral?: boolean; +} + +interface CompletionsQueryResult { + /** start offsets of the word that was completed */ + start: number | Position; + /** end offsets of the word that was completed */ + end: number | Position; + /** whether the completion is for a property or a variable */ + isProperty: boolean; + // TODO depends on completionsquery settings -> conditional types? + /** + * array of completions. When one of the `types`, `depths`, `docs`, `urls`, or `origins` + * options was passed, the array will hold objects with a `name` property (the completion text), + * and, depending on the options, `type`, `depth`, `doc`, `url`, and `origin` properties. + * When none of these options are enabled, the result array will hold plain strings. + */ + completions: string[] | Array<{ + name: string, + type?: string, + depth?: number, + doc?: string, + url?: string, + origin?: string + }>; +} + +/** Query the type of something. */ +export interface TypeQuery extends BaseQuery { + /** Query the type of something. */ + type: "type"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; + /** + * Set to `true` when you are interested in a function type. + * This will cause function types to win when something has multiple types. + * Default `false` + */ + preferFunction?: boolean; + /** + * Determines how deep the type string must be expanded. + * Nested objects will only display property types up to this depth, + * and be represented by their type name or a representation showing + * only property names below it. Default `0` + */ + depth?: number; +} + +interface TypeQueryResult { + /** A description of the type of the value. May be "?" when no type was found. */ + type: string; + /** Whether the given type was guessed, or should be considered reliable. */ + guess: boolean; + /** The name associated with the type. */ + name?: string; + /** When the inspected expression was an identifier or a property access, this will hold the name of the variable or property. */ + exprName?: string; + /** If the type had documentation associated with it, these will also be returned. */ + doc?: string; + /** If the type had urls associated with it, these will also be returned. */ + url?: string; + /** If the type had origin information associated with it, these will also be returned. */ + origin?: string; +} + +/** + * Asks for the definition of something. This will try, for a variable or property, + * to return the point at which it was defined. If that fails, or the chosen + * expression is not an identifier or property reference, it will try to return + * the definition site of the type the expression has. If no type is found, or the + * type is not an object or function (other types don’t store their definition site), + * it will fail to return useful information. + */ +export interface DefinitionQuery extends BaseQuery { + /** + * Asks for the definition of something. This will try, for a variable or property, + * to return the point at which it was defined. If that fails, or the chosen + * expression is not an identifier or property reference, it will try to return + * the definition site of the type the expression has. If no type is found, or the + * type is not an object or function (other types don’t store their definition site), + * it will fail to return useful information. + */ + type: "definition"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface DefinitionQueryResult { + /** The start position of the expression. */ + start?: number | Position; + /** The end position of the expression. */ + end?: number | Position; + /** The file in which the definition was defined. */ + file?: string; + /** A slice of the code in front of the definition Can be used to find a definition’s location in a modified file. */ + context?: string; + /** The offset from the start of the context to the actual definition. Can be used to find a definition’s location in a modified file. */ + contextOffset?: number; + /** If the definition had documentation associated with it, these will also be returned. */ + doc?: string; + /** If the definition had urls associated with it, these will also be returned. */ + url?: string; + /** If the definition had origin information associated with it, these will also be returned. */ + origin?: string; +} + +/** Get the documentation string and URL for a given expression, if any. */ +export interface DocumentationQuery extends BaseQuery { + /** Get the documentation string and URL for a given expression, if any. */ + type: "documentation"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface DocumentationQueryResult { + /** The documentation string of the definition or value, if any. */ + doc?: string; + /** The url of the definition or value, if any. */ + url?: string; + /** The origin of the definition or value, if any. */ + origin?: string; +} + +/** Used to find all references to a given variable or property. */ +export interface RefsQuery extends BaseQuery { + /** Used to find all references to a given variable or property. */ + type: "refs"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the expression. */ + end: number | Position; + /** Specify the location of the expression. */ + start?: number | Position; +} + +interface RefsQueryResult { + /** The name of the variable or property */ + name: string; + refs: Array<{ + file: string, + start: number | Position, + end: number | Position + }>; + /** for variables: a type property holding either "global" or "local". */ + type?: "global" | "local"; +} + +/** Rename a variable in a scope-aware way. */ +export interface RenameQuery extends BaseQuery { + /** Rename a variable in a scope-aware way. */ + type: "rename"; + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; + /** Specify the location of the variable. */ + end: number | Position; + /** Specify the location of the variable. */ + start?: number | Position; + /** The new name of the variable */ + newName: string; +} + +/** + * Returns an object whose `changes` property holds an array of `{file, start, end, text}` objects, which + * give the changes that must be performed to apply the rename. The client is responsible for doing the actual modification. + */ +interface RenameQueryResult { + /** Array of changes that must be performed to apply the rename. The client is responsible for doing the actual modification. */ + changes: Array<{ + file: string, + start: number | Position, + end: number | Position, + text: string + }>; +} + +/** Get a list of all known object property names (for any object). */ +export interface PropertiesQuery extends BaseQuery { + /** Get a list of all known object property names (for any object). */ + type: "properties"; + /** Causes the server to only return properties that start with the given string. */ + prefix?: string; + /** Whether the result should be sorted. Default `true` */ + sort?: boolean; +} + +interface PropertiesQueryResult { + /** The property names. */ + completions: string[]; +} + +/** Get the files that the server currently holds in its set of analyzed files. */ +export interface FilesQuery extends BaseQuery { + /** Get the files that the server currently holds in its set of analyzed files. */ + type: "files"; + docFormat?: never; + lineCharPositions?: never; +} + +interface FilesQueryResult { + /** The file names. */ + files: string[]; +} + +export interface Events { + /** When the server throws away its current analysis data and starts a fresh run. */ + reset(): void; + /** Before analyzing a file. file is an object holding {name, text, scope} properties. */ + beforeLoad(file: File): void; + /** After analyzing a file. */ + afterLoad(file: File): void; + /** + * Will be run right before a file is parsed, and passed the given text and options. If a handler + * returns a new text value, the origin text will be overriden. This is useful for + * instance when a plugin is able to extract JavaScript content from an HTML file. + */ + preParse(text: string, options: object): string | void; + /** Run right after a file is parsed, and passed the parse tree and the parsed file as arguments. */ + postParse(ast: ESTree.Program, text: string): void; + /** Run right before the type inference pass, passing the syntax tree and a scope object. */ + preInfer(ast: ESTree.Program, scope: Scope): void; + /** Run after the type inference pass. */ + postInfer(ast: ESTree.Program, scope: Scope): void; + /** + * Run after Tern attempts to find the type at the position end in the given file. + * A handler may return either the given type (already calculated by Tern and earlier "typeAt" passes) + * or an alternate type to be used instead. This is useful when + * a plugin can provide a more helpful type than Tern (e.g. within comments). + */ + typeAt(file: File, end: Position, expr: ESTree.Node, type: Type): Type | void; + /** Run at the start of a completion query. May return a valid completion result to replace the default completion algorithm. */ + completion(file: File, query: Query): CompletionsQueryResult | void; +} + +export const version: string; + +// ###### Plugins ######## + +/** + * This can be used to register an initialization function for the plugin with the given name. + * A Tern server, when configured to load this plugin, will call this initialization function, + * passing in the server instance and the options specified for the plugin (if any). This is the + * place where you register event handlers on the server, add type definitions, load other + * plugins as dependencies, and/or initialize the plugin’s state. + * + * See the server’s [list of events](http://ternjs.net/doc/manual.html#events) for ways to wire up plugin behavior. + */ +export function registerPlugin(name: string, init: (server: Server, options?: ConstructorOptions) => void): void; + +interface Desc { + run(Server: Server, query: QueryRegistry[T]["query"], file?: File): QueryRegistry[T]["result"]; + takesfile?: boolean; +} + +/** + * Defines a new type of query with the server. The `desc` object is a property describing the request. + * It should at least have a `run` property, which holds a function fn(Server, query) that will + * be called to handle queries with a type property that matches the given `name`. It may also have + * a `takesFile` property which, if true, will cause the server to try and resolve the file on which + * the query operates (from its file property) and pass that (a {name, text, scope, ast} object) as + * a third argument to the run function. You will probably need to use the inference + * module’s API to do someting useful in this function. + * + * To be able to use this function and the `request` function in a useful way, you probably want + * to define an interface for the query and the result of the query and extend the interface `QueryRegistry` via + * [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) + * in the following manner: + * + * ```typescript + * declare module "tern/lib/tern" { + * interface QueryRegistry { + * [CustomQueryType]: { + * query: CustomQuery + * result: CustomQueryResult + * } + * } + * } + * ``` + * _Note that your query interface should extend_ `BaseQuery` _and that its_ `type` _property has to be spelled + * exactly like the key in the_ `QueryRegistry` _interface._ + */ +export function defineQueryType(name: T, desc: Desc): void; diff --git a/types/tern/test/tern.test.ts b/types/tern/test/tern.test.ts new file mode 100644 index 0000000000..87cfee1ee6 --- /dev/null +++ b/types/tern/test/tern.test.ts @@ -0,0 +1,55 @@ +import * as tern from "tern"; + +const server: tern.Server = null as any; + +server.request({ + query: { + type: "completions", + file: "", + end: 0 + } +}, (error, response) => { + if (response && response.isProperty) { + // + } +}); + +server.request({ +}, (error, response) => { + // $ExpectError + if (response && response.isProperty) { + // + } +}); + +declare module "tern/lib/tern" { + interface QueryRegistry { + someUnknownType: { + query: { + type: "someUnknownType" + }, + result: { + abc: boolean + } + }; + } +} + +server.request({ + query: { + type: "someUnknownType" + } +}, (error, response) => { + if (response && response.abc) { + // + } +}); + +server.request({ + query: undefined +}, (error, response) => { + // $ExpectError + if (response && response.isProperty) { + // + } +}); diff --git a/types/tern/tsconfig.json b/types/tern/tsconfig.json new file mode 100644 index 0000000000..24e87522b3 --- /dev/null +++ b/types/tern/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", + "lib/tern/index.d.ts", + "lib/infer/index.d.ts", + "test/tern.test.ts" + ] +} \ No newline at end of file diff --git a/types/tern/tslint.json b/types/tern/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/tern/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/webpack-subresource-integrity/index.d.ts b/types/webpack-subresource-integrity/index.d.ts new file mode 100644 index 0000000000..d47d7d2275 --- /dev/null +++ b/types/webpack-subresource-integrity/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for webpack-subresource-integrity 1.2 +// Project: https://github.com/waysact/webpack-subresource-integrity +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/webpack-subresource-integrity-typings +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; + +declare namespace WebpackSubresourceIntegrityPlugin { + interface Options { + /** + * Default value: true + * When this value is falsy, the plugin doesn't run and no integrity values are calculated. It is recommended to disable the plugin in development mode. + */ + enabled?: boolean; + + /** + * An array of strings, each specifying the name of a hash function to be used for calculating integrity hash values. For example, ['sha256', 'sha512']. + */ + hashFuncNames: string[]; + } +} + +declare class WebpackSubresourceIntegrityPlugin extends Plugin { + constructor(options?: WebpackSubresourceIntegrityPlugin.Options); +} + +export = WebpackSubresourceIntegrityPlugin; diff --git a/types/webpack-subresource-integrity/tsconfig.json b/types/webpack-subresource-integrity/tsconfig.json new file mode 100644 index 0000000000..5461016c11 --- /dev/null +++ b/types/webpack-subresource-integrity/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", + "webpack-subresource-integrity-tests.ts" + ] +} diff --git a/types/webpack-subresource-integrity/tslint.json b/types/webpack-subresource-integrity/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/webpack-subresource-integrity/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts b/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts new file mode 100644 index 0000000000..810893429c --- /dev/null +++ b/types/webpack-subresource-integrity/webpack-subresource-integrity-tests.ts @@ -0,0 +1,15 @@ +import * as webpack from 'webpack'; +import SriPlugin = require('webpack-subresource-integrity'); + +const config: webpack.Configuration = { + plugins: [ + new SriPlugin(), + new SriPlugin({ + hashFuncNames: ['sha256', 'sha384'] + }), + new SriPlugin({ + enabled: false, + hashFuncNames: ['sha256'] + }) + ] +};